小明思考

高性能服务器端计算
posts - 70, comments - 428, trackbacks - 0, articles - 0
  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

SendMessage 和 SendMessageTimeout

Posted on 2006-07-21 09:50 小明 阅读(10078) 评论(5)  编辑 收藏 引用 所属分类: Win32
SendMessageTimeout并不是简单在SendMessage加上Timeout的功能。

MSDN上面有一段文字是这样说的

If the specified window was created by the calling thread, the window procedure is called immediately as a subroutine. If the specified window was created by a different thread, the system switches to that thread and calls the appropriate window procedure. Messages sent between threads are processed only when the receiving thread executes message retrieval code. The sending thread is blocked until the receiving thread processes the message. However, the sending thread will process incoming nonqueued messages while waiting for its message to be processed. To prevent this, use SendMessageTimeout with SMTO_BLOCK set. For more information on nonqueued messages, see Nonqueued Messages.


翻译一下:

SendMessage : 如果指定窗口由调用线程创建,那么窗口过程会被当成一个子程序立即调用。如果指定窗口由另外一个线程创建,那么系统会切换到那个线程,并且调用合适的窗口过程。在线程之间传递的消息仅仅当接收线程执行message retrieval code才会被处理。发送线程会被堵塞直到接收线程处理完消息。但是,发送线程在等待的同时会处理收到的nonqueued messages 。为了阻止这一点,使用带有SMTO_BLOCK参数 的SendMessageTimeout .

=================================华丽的分割线===========================

我曾经遇到这个问题,我调用SendMessage向另外一个线程窗口发message,本来以为他会一直block住,但是他却调用了另外一个消息的处理程序,导致了行为不正确。所以一定要小心使用SendMessage发给其他线程的窗口。

我修改了一下,把
pWnd->SendMessage(MSG_LOG_MESSAGE, nMsgType, (LPARAM)(LPCTSTR)m_cstrMessage);
改成了
HWND hWnd = pWnd->GetSafeHwnd();
::SendMessageTimeout(hWnd,MSG_LOG_MESSAGE, nMsgType, (LPARAM)(LPCTSTR)m_cstrMessage,SMTO_BLOCK,15000,0);
解决了这个bug.

Feedback

# re: SendMessage 和 SendMessageTimeout  回复  更多评论   

2006-12-27 15:02 by honey
好!!!虽然我看不懂写些什么

# re: SendMessage 和 SendMessageTimeout  回复  更多评论   

2009-02-12 14:50 by lijinyan3000
没看明白啊。。。可能是我水平不够。。。

# re: SendMessage 和 SendMessageTimeout  回复  更多评论   

2011-11-17 10:56 by 寂寞男生
哥也没看懂呀!!!

# re: SendMessage 和 SendMessageTimeout  回复  更多评论   

2012-02-20 15:59 by zhgkun
首先英文翻译的的比较准确、专业!
正在研究SendMessage和SendMessageTImeOut区别,其中一个例子是,启动应用程序新实例前,向已存在的实例发送copydata消息做一些处理,原先用的是sendmessage,现在觉得用sendmessagetimeout应该更稳妥一些

# re: SendMessage 和 SendMessageTimeout  回复  更多评论   

2012-02-20 16:21 by zhgkun
LRESULT SendMessageTimeout(
HWND hWnd, // handle to window
UINT Msg, // message
WPARAM wParam, // first message parameter
LPARAM lParam, // second message parameter
UINT fuFlags, // send options
UINT uTimeout, // time-out duration
PDWORD_PTR lpdwResult // return value for synchronous call
);

fuFlags
[in] Specifies how to send the message. This parameter can be one or more of the following values

SMTO_ABORTIFHUNG
Returns without waiting for the time-out period to elapse if the receiving process appears to be in a "hung" state.

顺便翻译一下最后一句
“如果接收进程处于挂起状态,不再等待(超时)直接返回”

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理