PostMessage和SendMessage的区别

本文详细解释了Windows编程中SendMessage与PostMessage两个函数的主要区别,包括它们的工作方式、线程同步特性以及在不同线程间消息传递的行为差异。

http://100926.blog.sohu.com/187003740.html


区别1: 

MSDN讲SendMessage用法时,有一段话讲述了两者的区别,

This function sends the specified message to a window or windows. SendMessage calls the window procedure for the specified window and does not return until the window procedure has processed the message. The PostMessage function, in contrast, posts a message to a thread's message queue and returns immediately.

翻译成中文的意思是:

(SendMessage)这个函数发送指定消息到窗口,SendMessage调用窗口程序来处理消息,直到窗口程序处理完消息才返回。PostMessage函数,相反,发送消息给线程消息队列并立即返回。

区别2:

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.

翻译:如果发送的消息码在WM_USER之下(非自定义消息)且消息参数中带有指针,那么PostMessage,SendNotifyMessage,SendMessageCallback这些异步消息发送函数将会调用失败。最好不要用PostMessage发送带有指针参数的消息。

区别3:

如果在同一个线程中,PostMessage发送消息时,消息要先放入线程的消息队列,然后通过消息循环Dispatch到目标窗口。SendMessage发送消息时,系统直接调用目标窗口的消息处理程序,并将结果返回。SendMessage在同一线程中发送消息并不入线程消息队列。如果在不同线程内。最好用PostThreadMessage代替PostMessage,他工作的很好。SendMessage发送消息到目标窗口所属的线程的消息队列,然后发送消息的线程等待(事实上,他应该还在做一些监测工作,比如监视QS_SENDMESSAGE标志),直到目标窗口处理完并且结果返回,发送消息的线程才继续运行。这是SendMessage的一般情况,事实上,处理过程要复杂的多。比如,当发送消息的线程监测到有别的窗口 SendMessage一个消息到来时,他直接调用窗口处理过程(重入),并将处理结果返回(这个过程不需要消息循环中GetMessage等的支持)。

补充:

今天看<<win32多线程程序设计>>一书,讲<同步控制>一节时,有关PostMessage()、SendMessage()和异步和同步,这段话可以进一步加深理解,所以摘录一下:

 

注释:让我对同步和异步做个说明,当程序1调用程序2时,程序1停下来不动,程序2完成回到程序1来,程序1才继续下去,这就是所谓的synchronous(同步),如果程序1调用程序2后,径直继续自己的下一个动作那么两者之间就是所谓的asynchronous(异步),Win32 API 中的SendMessage()就是同步行为,而PostMessage()就是异步行为;

在Windows系统中,PostMessage()是把消息放到对方的消息队列中,然后不管三七二十一,就回到原调用点继续执行,所以这是异步行为,而SendMessage()根本就是直接调用窗口之窗口函数,除非该窗口函数结束,是不会回到原调用点的,所以它是同步行为。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值