Windows 消息循环和 WTL
我正在尝试了解 WTL 的工作方式,而消息循环现在让我感到困惑。
例如这个代码片段: link
首先创建窗口,然后创建消息泵启动。怎么会起作用呢? CreateEx、UpdateWindow 等不是应该发送自己的不可见消息,如 WM_CREATE/WM_PAINT/WM_NCPAINT 吗?如果消息泵没有初始化,它们会被抛出哪里?如果您创建一个窗口,启动消息循环,然后关闭该窗口,但想在其位置创建一个新窗口,会发生什么情况? PostQuit 退出循环并且您必须创建一个新循环?
I'm trying to understand the way WTL works, and message loops are confusing me right now.
For example this code fragment: link
The window is first created and after that the message pump is started. How come it works? Isn't the CreateEx, UpdateWindow and so on supposed to send their own invisible messages like WM_CREATE/WM_PAINT/WM_NCPAINT? Where are they thrown if the message pump is not initialized? What happens if you create a window, start message loop, then close the window, but want to create a new one in it's place? PostQuit exits the loop and you have to create a new one?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
关于消息发送,
CreateWindow
直接发送消息,就像使用SendMessage
一样。如果您做过很多 Windows 编程,您可能会以这种方式直接向控件发送消息,并且事情会立即发生,而不需要运行消息泵; Windows 本身也会执行此操作。至于
PostQuitMessage
问题,通常的策略是在消息循环中进行其他一些检查,以查看应用程序是否应该退出。例如,您可以维护一个打开窗口的计数器,然后在有 0 个打开窗口时退出,而不是在窗口关闭时发布退出消息并在消息循环中等待WM_QUIT
。WM_QUIT
没有什么神奇之处,除了可以使用PostQuitMessage
发布它并使用GetMessage
(等等)轻松检查它的便捷方式。 ) 函数。您可以不使用它,并因其他原因决定退出您的程序。Regarding the message sending,
CreateWindow
sends the message directly, as ifSendMessage
were used. If you've done much Windows programming, you'll probably have sent messages to controls directly in this way, and had things happen immediately without needing the message pump to run; Windows will do this itself, too.As for the
PostQuitMessage
issue, the usual tactic is to have some other check in the message loop to see if the application should exit. For example, rather than posting a quit message on window close and waiting forWM_QUIT
in the message loop, you could maintain a counter of open windows then just quit if there are 0 open windows.There is nothing magic about
WM_QUIT
, except for the convenient way you can post it withPostQuitMessage
and easily check for it with theGetMessage
(etc.) functions. You are free not to use it and decide to exit your program for some other reason.理解发布消息 (PostMessage) 和发送消息 (SendMessage) 之间的区别在这里很重要。 Windows 直接调用窗口过程来发送消息,它们不是由消息循环调度的。这就是在消息循环启动之前处理 WM_CREATE 和 WM_SHOWWINDOW 的方式。 WM_QUIT、WM_PAINT、WM_KEYDOWN 和 WM_MOUSEMOVE 是发布的消息的示例。
Understanding the difference between posting messages (PostMessage) and sending messages (SendMessage) is important here. Windows calls the window procedure directly for sent messages, they are not dispatched by the message loop. Which is how WM_CREATE and WM_SHOWWINDOW can be processed before the message loop is started. WM_QUIT, WM_PAINT, WM_KEYDOWN and WM_MOUSEMOVE are examples of messages that are posted.