The TApplication Type's OnMessage Event
Another technique for handling messages is to use TApplication's OnMessage event. When you assign a procedure to OnMessage, that procedure is called whenever a message is pulled from the queue and about to be processed. This event handler is called before Windows itself has a chance to process the message. The Application.OnMessage event handler is of TMessageEvent type and must be defined with a parameter list, as shown here:
procedure SomeObject.AppMessageHandler(var Msg: TMsg; var Handled: Boolean);
All the message parameters are passed to the OnMessage event handler in the Msg parameter. (This parameter is of the Windows TMsg record type.) The Handled field requires you to assign a Boolean value indicating whether you've handled the message.
You can create an OnMessage event handler by using a TApplicationEvents component from the Additional page of the Component palette. Here's an example of such an event handler:
var NumMessages: Integer; procedure TForm1.ApplicationEvents1Message(var Msg: tagMSG; var Handled: Boolean); begin Inc(NumMessages); Handled := False; end;
One limitation of OnMessage is that it's executed only for messages pulled out of the queue, and not for messages sent directly to the window procedures of windows in your application. You can work around this limitation by hooking into the application window procedure.