SendMessage Function
The SendMessage
function sends the specified message to one or more
destinations. This function calls the window procedure for each intended
recipient window and does not return until each window procedure has
processed the message.
LRESULT SendMessage(
HWND hWnd,
UINT Msg,
WPARAM wParam,
LPARAM lParam
);
Parameter | Type | Description |
---|---|---|
hWnd |
HWND |
A handle to the destination window. If this parameter is
HWND_BROADCAST ((HWND)0xffff), the message is sent to all top-level
windows in the system, including disabled and invisible overlapped windows.
The message does not appear to be sent to the sender's process
unless the sender's process is a top-level window.
|
Msg |
UINT |
The message to be sent. |
wParam |
WPARAM |
Additional message-specific information. |
lParam |
LPARAM |
Additional message-specific information. |
Return Value
The return value specifies the result of the message processing and depends on the message sent.
SendMessage
does not invoke the thread's message-processing
loop, so it cannot be used to send messages that require the thread's
message-processing loop to process. To send a message that requires
the thread's message-processing loop to be processed, use the
SendNotifyMessage
function.
If the hWnd
parameter specifies a window created by another thread,
the system sends the message to the thread that created the window and
the calling thread waits until the thread receives and processes the message.
If the hWnd
parameter specifies a top-level window created by
another thread, the system queues the message to the thread that created
the window. The message is processed only when the thread's message queue
contains the message and the thread calls a message-processing function.
Example
The following example demonstrates how to send a custom message to a window.
#include <windows.h>
// Define a custom message
#define WM_MY_CUSTOM_MESSAGE (WM_USER + 1)
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {
HWND hWndTarget = FindWindow(NULL, "Target Window Title"); // Replace with actual window title
if (hWndTarget != NULL) {
// Send the custom message with some data
LRESULT result = SendMessage(hWndTarget, WM_MY_CUSTOM_MESSAGE, 123, (LPARAM)"Hello from SendMessage!");
if (result != 0) {
MessageBox(NULL, "Message sent successfully!", "Success", MB_OK);
} else {
MessageBox(NULL, "Failed to send message.", "Error", MB_OK | MB_ICONERROR);
}
} else {
MessageBox(NULL, "Target window not found.", "Error", MB_OK | MB_ICONERROR);
}
return 0;
}