问题描述
当我将 SendMessage
函数与 HWND_BROADCAST
一起使用时,应用程序挂断了.应用程序很长时间没有响应.
When I use the SendMessage
function with HWND_BROADCAST
, the application hangs up. There is no response from the application for long time.
谁能解释一下为什么?
推荐答案
当有一个具有顶级窗口的进程,但没有在创建该窗口的线程上调用 GetMessage 或 PeekMessage 时,就会发生这种情况.
This will happen when there is an process that has a top level window, but isn't calling GetMessage or PeekMessage on the thread that created the window.
为了与 Windows 3.0 向后兼容,在系统中的所有顶级窗口都响应您的广播之前,SendMessage 不会返回.在 Windows 多线程之前,这种行为是有意义的,因为 SendMessage(),即使发送到其他进程也永远不会阻塞.
For backward compatibility with Windows 3.0, SendMessage will not return until all of the top level windows in the system have responded to your broadcast. This behavior made sense back before Windows was multithreaded, because SendMessage(), even when sending to other processes would never block.
但是从 Win32 开始,当你向另一个进程中的窗口发送消息时,实际发生的事情是你的线程阻塞,直到另一个进程中的线程唤醒并处理消息.如果该线程很忙,或者只是没有发送消息,那么您将永远等待.
But beginning with Win32, when you SendMessage to a window in another process, what actually happens is your thread blocks until the thread in the other process wakes up and handles the message. If that thread is busy, or just not pumping messages, then you wait forever.
因此,当您使用 HWND_BROADCAST 或以其他方式向其他进程拥有的窗口发送消息时,您应该始终使用 SendNotifyMessage
或 SendMessageTimeout
.
For that reason you should always use SendNotifyMessage
or SendMessageTimeout
when you use HWND_BROADCAST, or are otherwise sending messages to windows owned by other processes.
这篇关于SendMessage(HWND_BROADCAST, ....) 挂起的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!