c++builder 将Handle句柄转成对象

#pragma pack(1)
struct TObjectInstance
{
  byte Code;           //{ 短跳转 $E8 }
  int Offset;       //{ CalcJmpOffset(Instance, @Block^.Code); }
  TObjectInstance * Next; //{ MainWndProc 地址 }
  void * Self;         //{ 控件对象地址 }
};
typedef TObjectInstance * PObjectInstance ;

TWinControl * GetInstanceFromhWnd(HWND hWnd)
{
  PObjectInstance wc;

  wc     = (PObjectInstance)GetWindowLong(hWnd, GWL_WNDPROC);
  if (wc != NULL )
    return (TWinControl *)wc->Self;
  else
    return NULL;
}
void __fastcall TForm1::Button7Click(TObject *Sender)
{
   TWinControl * p = GetInstanceFromhWnd(Edit1->Handle);
   TEdit * f = dynamic_cast(p);
   Button7->Caption = f->Text;
}

窗口回调函数指针,相邻的第10个字节处,是消息对象指针,如果不想用#pragma pack(1)改变编译器属性的话,可以用如下方法:

struct obj
{
   byte a1;
   byte a2;
   byte a3;
   byte a4;
   byte a5;
   byte a6;
   byte a7;
   byte a8;
   byte a9;
   byte a10;
   byte a11;
   byte a12;
   byte a13;
};

TWinControl * GetInstanceFromhWnd(HWND hWnd)
{
  obj * wc1     = (obj *)GetWindowLong(hWnd, GWL_WNDPROC);

  if (wc1 != NULL )
  {
    int c1 =  wc1->a13;
    int c2 =  wc1->a12;
    int c3 =  wc1->a11;
    int c4 =  wc1->a10;

    int p1 = int(c1 << 24) + int(c2 << 16) +int(c3 << 8) + c4;
    return (TWinControl *)p1;
  }
  else
    return NULL;
}
void __fastcall TForm1::Button7Click(TObject *Sender)
{
   TWinControl * p = GetInstanceFromhWnd(Edit1->Handle);
   TEdit * f = dynamic_cast(p);


   Button7->Caption = f->Text;
}
效果同上,用了不同的结构体获取对象偏移指针,在C++builder中,用下面这句也可以:

TForm * f = (TForm * )FindControl(Handle);


你可能感兴趣的:(C++Builder6)