Sending Your Own Messages
Just as Windows sends messages to your application's windows, you will occasionally need to send messages between windows and controls within your application. Delphi provides several ways to send messages within your application, such as the Perform() method (which works independently of the Windows API) and the SendMessage() and PostMessage() API functions.
The Perform() Method
VCL provides the Perform() method for all TControl descendants; Perform() enables you to send a message to any form or control object given an instance of that object. The Perform() method takes three parametersa message and its corresponding lParam and wParamand is defined as follows:
function TControl.Perform(Msg: Cardinal; WParam, LParam: Longint): Longint;
To send a message to a form or control, use the following syntax:
RetVal := ControlName.Perform(MessageID, wParam, lParam);
Perform() is synchronous in that it doesn't return until the message has been handled. The Perform() method packages its parameters into a TMessage record and then calls the object's Dispatch() method to send the messagebypassing the Windows API messaging system. The Dispatch() method is described later in this chapter.
The SendMessage() and PostMessage() API Functions
Sometimes you need to send a message to a window for which you don't have a Delphi object instance. For example, you might want to send a message to a non-Delphi window, but you have only a handle to that window. Fortunately, the Windows API offers two functions that fit this bill: SendMessage() and PostMessage(). These two functions are essentially identical, except for one key difference: SendMessage(), similar to Perform(), sends a message directly to the window procedure of the intended window and waits until the message is processed before returning; PostMessage() posts a message to the Windows message queue and returns immediately.
SendMessage() and PostMessage() are declared as follows:
function SendMessage(hWnd: HWND; Msg: UINT; wParam: WPARAM; lParam: LPARAM): LRESULT; stdcall; function PostMessage(hWnd: HWND; Msg: UINT; wParam: WPARAM; lParam: LPARAM): BOOL; stdcall;
hWnd is the window handle for which the message is intended.
Msg is the message identifier.
wParam is 32 bits of additional message-specific information.
lParam is 32 bits of additional message-specific information.
NOTE
Although SendMessage() and PostMessage() are used similarly, their respective return values are different. SendMessage() returns the result value of the message being processed, but PostMessage() returns only a BOOL that indicates whether the message was placed in the target window's queue. Another way to think of this is that SendMessage() is a synchronous operation, whereas PostMessage() is asynchronous.