原文:http://delphi.about.com/od/windowsshellapi/a/receive-windows-messages-in-custom-delphi-class-nonwindowed-control.htm
Windows消息用来在Windows系统与应用程序之间,或应用程序与应用程序之间进行交互通迅。例如:当用户关闭应用程序窗口时,WM_CLOSE消息就会发送到相应的窗口。
对于一个接收Windows消息的应用来说,必须提供一个窗口来接收消息。通常它会是应用程序的主窗口,你写一个过程处理特定消息,比如WM_NCHitTest,那么就可以处理该消息 。但是如果没有窗口来接收消息,你要一个从TObject继承的类来处理消息,又该怎么办呢?
在类TMyObject = class(TObject)中处理Windows消息
一个从TWinControl继承的Delphi控件是可以接收Windows消息的。TObject类并没有提供一个窗口句柄,因此,从TObject继承的类是没有办法处理Windows消息 的,至少默认情况下是这样的。为了接收Windows消息 ,你需要为你的自定义类提供一个窗口句柄来接收Windows消息。关键是使用classes.pas中定义的下面介绍的方法:
AllocateHWnd(WndMethod : TWndMethod).
AllocateHWnd用来创建一个不与窗口控件关联的窗口
WndMethod : TWndMethod
用来指定生成的窗口响应消息的窗口过程。
DeallocateHWnd
DeallocateHWnd 用来销毁AllocateHWnd创建的窗口。
下面的TMsgReceiver是从TObject继承的类,并且能处理Windows消息。
interface TMsgReceiver = class(TObject) private fMsgHandlerHWND : HWND; procedure WndMethod(var Msg: TMessage); public constructor Create; destructor Destroy; override; end; implementation constructor TMsgReceiver.Create; begin inherited Create; fMsgHandlerHWND := AllocateHWnd(WndMethod); end; destructor TMsgReceiver.Destroy; begin DeallocateHWnd(fMsgHandlerHWND); inherited; end; procedure TMsgReceiver.WndMethod(var Msg: TMessage); begin if Msg.Msg = WM_MY_UNIQUE_MESSAGE then begin //do something end else Msg.Result := DefWindowProc(fMsgHandlerHWND, Msg.Msg, Msg.wParam, Msg.lParam); end;
处理来自其它应用的消息
通过上面的代码,假设其它应用使用RegisterWindowMessage注册了Windows消息,你现在也能处理来自其它应用的消息。RegisterWindowMessage通常用来注册互相协作的应用程序间的消息.
发送消息的应用可能有如下代码:
WM_MY_APP_MESSAGE := RegisterWindowMessage('MSG_MY_APP_MESSAGE');
procedure TClickSendForm.FormMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin PostMessage(HWND_BROADCAST, WM_MY_APP_MESSAGE, x, y); end;
procedure TMsgReceiver.WndMethod(var Msg: TMessage); begin if Msg.Msg = WM_MY_UNIQUE_MESSAGE then begin Point.X := Msg.LParam; Point.Y := Msg.WParam; // just to have some "output" Windows.Beep(Point.X, Point.Y); end else Msg.Result := DefWindowProc(fMsgHandlerHWND, Msg.Msg, Msg.wParam, Msg.lParam); end;
"Point"是TMsgReceiver的一个字段. TMsgReceiver接收到其它的应用程序用户在窗口的哪里点击了鼠标。WM_MY_UNIQUE_MESSAGE也需要在TMsgReceiver中进行注册。
源代码下载:http://delphi.about.com/library/code/tmsgreceiver.zip