c++ - 如何一次创建、处理和销毁多个窗口?

标签 c++ windows winapi window

我听说要在我的 C++ 应用程序中创建多个窗口,我需要做的就是创建任意数量的 HWND,然后为每个窗口使用 CreateWindowEx (),以及适当的窗口类等。
我已经做到了,所以这不是问题。

现在,通常,我会为我的应用程序制作这种消息循环:

MSG msg;
while(1)
{
    while(PeekMessage(&msg, hWnd, 0, 0, PM_REMOVE))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
    if(msg.message == WM_QUIT)
        break;
}

(这应该是正确的,是吗?)

但是现在我有 3 个窗口,我的消息循环看起来像这样:

MSG msg;
while(1)
{
    while(PeekMessage(&msg, hWnd, 0, 0, PM_REMOVE) || PeekMessage(&msg, hConWnd, 0, 0, PM_REMOVE) || PeekMessage(&msg, hStatWnd, 0, 0, PM_REMOVE))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
    if(msg.message == WM_QUIT)
        break;
}

所以它会检查所有窗口的消息,对吗?

现在我的问题是,这是为多个窗口获取消息的正确方法吗?
另外,我听说对不同的窗口使用不同的 WndProc 不好,这是真的吗?如果是的话,为什么? (如果我想为每个窗口设置不同的行为,如何只使用一个?)

最后,我该如何退出我的应用程序,以便在关闭其中一个窗口(任何窗口)时,所有窗口都将适当关闭?

最佳答案

PeekMessage(&msg, NULL, ... 将执行您需要的操作。msg 将接收需要发送消息的窗口句柄,因此单个 API调用适用于所有现有窗口。

hWnd [in, optional]

A handle to the window whose messages are to be retrieved. The window must belong to the current thread.

If hWnd is NULL, PeekMessage retrieves messages for any window that belongs to the current thread, and any messages on the current thread's message queue whose hwnd value is NULL (see the MSG structure). Therefore if hWnd is NULL, both window messages and thread messages are processed.

也就是说,您可以继续使用原来的消息泵送循环,只是不要将其限制在特定窗口。

问题:

Now my question is, is this the correct way of getting messages for multiple windows?

消息循环,您的或某人的调度消息。您在窗口的 WndProc 上处理它们,而不必过多考虑究竟是谁传递消息并调用您的 WndProc。它同样适用于单个窗口和多个窗口。

Also, I've heard that using different WndProcs for different windows isn't good, is this true, and if so, why? (And how to use just one, if I want a bit different behavior for each window?)

不真实。

And finally, how do I exit my application so that if one of the windows is closed (any window), all will be closed, appropriately?

WM_QUIT 在您的示例中发布时,消息循环就会中断。然后你应该销毁 window 并退出。

关于c++ - 如何一次创建、处理和销毁多个窗口?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14571396/

相关文章:

c++ - Makefile:7:目标(在同一规则中多次给出

c++ - 避免模​​板特化中的构造函数重复

java - 从 Java 中生成的文件路径在 Android 中创建的 File 对象上的 file.getName() 产生奇怪的结果

linux - 使用cmake与工具链文件交叉编译时如何使用find_package?

winapi - 使用 CreateProcess 函数启动时,cmd.exe 在某些情况下不会终止

c++ - 如何在 STL map 内迭代 STL map ?

c++ - 禁用标准 :string's SSO

java - 我想在 Mac OS/Windows 的系统启动时运行我的 Java 程序。我怎样才能做到这一点?

c++ - 通过命名管道发送 DWORD

c++ - 来自 NtCreateFile 的 STATUS_INVALID_PARAMETER