今天用實例解釋一下SendMessage PostMessage 原理和區別:
向按鈕(Button)發送單擊:
SendMessage:
SendMessage(Button1.Handle, WM_LBUTTONDOWN, 0, 0);
SendMessage(Button1.Handle, WM_LBUTTONUP, 0, 0);
PostMessage:
PostMessage(Button1.Handle, WM_LBUTTONUP, 0, 0);
這2者都可以
但是向Edit發送字符串SendMessage可以,PostMessage就不行
Str := 'ABC';
PostMessage(Edit1.Handle, WM_SETTEXT, 0, LPARAM(str)); //不行
SendMessage(Edit1.Handle, WM_SETTEXT, 0, LPARAM(str)); //行
在MSDN中,SendMessage解釋如爲:The SendMessage function sends the specified message to a window or windows. It calls the window procedure for the specified
window and does not return until the window procedure has processed the message.
翻譯成中文爲:SendMessage函數將指定的消息發到窗口。它調用特定窗口的窗口處理函數,並且不會立即返回,直到窗口處理函數處理了這個消息。
再看看PostMessage的解釋: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.
翻譯成中文爲:PostMessage函數將一個消息放入與創建這個窗口的消息隊列相關的線程中,並立刻返回不等待線程處理消息。
仔細看完MSDN解釋,我們瞭解到,SendMessage的確是發送消息,然後等待處理完成返回,但發送消息的方法爲直接調用消息處理函數(即WndProc函數),按照函數調用規則,肯定會等消息處理函數返回之後,SendMessage才返回。而PostMessage卻沒有發送消息,PostMessage是將消息放入消息隊列中,然後立刻返回,至於消息何時被處理,PostMessage完全不知道,此時只有消息循環知道被PostMessage的消息何時被處理了。
SendMessage可以理解爲,SendMessage函數發送消息,等待消息處理完成後,SendMessage才返回。稍微深入一點,是等待窗口處理函數返回後,SendMessage就返回了。
PostMessage可以理解爲,PostMessage函數發送消息,不等待消息處理完成,立刻返回。稍微深入一點,PostMessage只管發送消息,消息有沒有被送到則並不關心,只要發送了消息,便立刻返回。