SendMessage(),PostMessage(),PostThreadMessage ()使用

来源:互联网 发布:淘宝几毛钱的东西 编辑:程序博客网 时间:2024/06/11 20:44

MSDN说明:
SendMessage():
Sends the specified message to a window or windows. The SendMessage function calls the window procedure for the specified window and does not return until the window procedure has processed the message.
To send a message and return immediately, use the SendMessageCallback or SendNotifyMessage function. To post a message to a thread’s message queue and return immediately, use the PostMessage or PostThreadMessage function.
给指定窗口(一个或多个窗口)发送消息,并等待窗口过程处理完消息后才返回,
如果要立即返回,使用SendMessageCallback()或者SendNotifyMessage();
如果要给指定线程发送队列消息并立即返回,使用PostMessage ()或PostThreadMessage();

SendMessage()原型:

LRESULT SendMessage(HWND hWnd,UINT Msg,WPARAM wParam,LPARAM lParam);

参数:
HWND hWnd,
接收消息的窗口句柄
UINT Msg,
消息

PostMessage():
MSDN说明:
The PostMessage function places (posts) a message in the message queue associated with the thread that created the specified window and returns without waiting for the thread to process the message.
To post a message in the message queue associated with a thread, use the PostThreadMessage function.
PostMessage()放置一条消息到创建指定窗口的线程消息队列中,并立即返回;
如果要给某个线程(一般是次线程)消息队列放置一条消息,使用PostThreadMessage ();

PostMessage()函数原型:

BOOL PostMessage( HWND hWnd,UINT Msg,WPARAM wParam,LPARAM lParam)

参数:
HWND hWnd,
接收消息的窗口句柄,若指定为NULL,则是给当前线程发送消息;若指定为HWND_BROADCAST,则给所有顶层窗口发送消息,不发送给子窗口。
UINT Msg,
消息

PostThreadMessage ()原型:

BOOL PostThreadMessage(DWORD idThread,UINT Msg,WPARAM wParam,LPARAM lParam);

参数:
DWORD idThread,
接收消息的线程的线程标识码
UINT Msg,
消息

举例:
ChaltestDlg是程序主窗口,也即主线程产生的窗口,在某个子线程中有以下代码:
hwnd=(ChaltestDlg * )AfxGetApp()->GetMainWnd();
hwnd->PostMessage(WM_PROCESS_TIMEOUT,0,0);

执行这段代码后,子线程则会给主线程发送一条WM_PROCESS_TIMEOUT(自定义的消息)消息,并立即返回;
或者
SendMessage(hwnd, WM_PROCESS_TIMEOUT,0,0);
不同的是,执行此函数后,停止执行该语句后面的语句,只有当该消息被接受者(hwnd指向的窗口过程)执行完后才继续执行其后面的语句,即不立即返回;

总结:
1. SendMessage(),PostMessage(),PostThreadMessage ()均可以在不同线程间发送消息,但消息的接收者标识码不同,SendMessage(),PostMessage(),使用窗口句柄,PostThreadMessage ()使用线程标识码;
2. SendMessage()发送的是非队列消息,其处理是由窗口过程处理,立即处理,PostMessage(),PostThreadMessage ()发送的是队列消息,非立即处理,
3. SendMessage()等待消息处理完才返回,PostMessage(),PostThreadMessage ()立即返回。

0 0
原创粉丝点击