让AllocateHwnd接受一般函数地址作参数(105篇博客)

http://www.xuebuyuan.com/1889769.html

Classes单元的AllocateHWnd函数是需要传入一个处理消息的类的方法的作为参数的,原型:

function AllocateHWnd(Method: TWndMethod): HWND;

很多时候,我们想要创建一个窗口,而又不想因为这个参数而创建一个类,怎么办?
换句话说,就是能不能使传入的参数是个普通的函数而不是类的方法呢?答案是肯定的!
看看TWndMethod的声明:

type
  TWndMethod = procedure(var Message: TMessage) of object;

实际上类的方法在执行时,总是传入了对象这个参数。
即此方法共传了两个参数,根据Delphi默认的registry调用约定,寄存器eax传递对象,edx传递Message结构变量。

因此我们可以声明处理消息的函数的类型:

type
  TMyWndProc = procedure(AObject: TObject; var Message: TMessage);

我们自定义MyAllocateHWnd函数以接收这个类型的参数,内部调用AllocateHWnd:

function MyAllocateHWnd(Proc: TMyWndProc): HWND;
asm
  push 0// AObject
  push Proc// Message
  call AllocateHWnd
end;

如果直接调用AllocateHwnd(Proc)是不能通过编译的!

复制代码
var H: HWND;

procedure MyWndProc(AObject: TObject; var Message: TMessage);
begin
  if Message.Msg = WM_USER + 111 then
    ShowMessage('')
  else
    Message.Result := DefWindowProc(H, Message.Msg, Message.WParam, Message.LParam)
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  H := MyAllocateHWnd(MyWndProc)
end;

procedure TForm1.FormDestroy(Sender: TObject);
begin
  DeallocateHWnd(H);
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  SendMessage(H, WM_USER + 111, 0, 0);
end;
复制代码

 

复制代码
unit uMain;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
  System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;

type
  TForm1 = class( TForm )
    Button1 : TButton;
    procedure FormCreate( Sender : TObject );
    procedure FormDestroy( Sender : TObject );
    procedure Button1Click( Sender : TObject );
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1 : TForm1;

implementation


{$R *.dfm}

type
  TMyWndProc = procedure( AObject : TObject; var Message : TMessage );

var
  H : HWND;

function MyAllocateHWnd( Proc : TMyWndProc ) : HWND;
asm
  push 0  // AObject
  push Proc // Message
  call AllocateHWnd
end;

procedure MyWndProc( AObject : TObject; var Message : TMessage );
begin
  if message.Msg = WM_USER + 111 then
    ShowMessage( 'Receive Message!' )
  else
    message.Result := DefWindowProc( H, message.Msg, message.WParam,
      message.LParam )
end;

procedure TForm1.Button1Click( Sender : TObject );
begin
  PostMessage( H, WM_USER + 111, 0, 0 );
end;

procedure TForm1.FormCreate( Sender : TObject );
begin
  H := MyAllocateHWnd( MyWndProc );
end;

procedure TForm1.FormDestroy( Sender : TObject );
begin
  DeallocateHWnd( H );
end;

end.
复制代码

 

http://www.cnblogs.com/shangdawei/p/4015434.html

posted @ 2016-03-05 00:15  findumars  Views(295)  Comments(0Edit  收藏  举报