CreateWindow/CreateDialog 中的 HWND 可以从另一个线程获取 GetMessage 吗?

2021-12-18 00:00:00 windows multithreading c winapi c++

使用 Win32 API,是否可以在一个线程中创建一个窗口或对话框,然后从另一个线程为它收集事件?

HWND 是否与线程相关联?

尝试下面的人为示例,我从未看到 GetMessage() 触发.

<前>HWND g_hWnd;DWORD WINAPI myThreadProc(LPVOID lpParam){while(GetMessage(&msg, hWnd, 0, 0) > 0){...}}int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd){hWnd = CreateDialog(hInstance, MAKEINTRESOURCE(IDD_MYDIALOG), 0, myDlgProc);CreateThread(NULL, 0 myThreadProc, NULL, 0, NULL);...}

但在这里,我愿意.

<前>HWND g_hWnd;HINSTANCE g_hInstance;DWORD WINAPI myThreadProc(LPVOID lpParam){hWnd = CreateDialog(hInstance, MAKEINTRESOURCE(IDD_MYDIALOG), 0, myDlgProc);while(GetMessage(&msg, hWnd, 0, 0) > 0){...}}int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd){g_hInstance = hInstance;CreateThread(NULL, 0 myThreadProc, NULL, 0, NULL);...}

有人能解释一下我看到了什么吗?

解决方案

没有

GetMessage 在当前线程的输入队列上返回消息.HWND 参数是一个过滤器,因此 GetMessage 只返回当前线程的输入队列中用于该窗口的消息.

Windows 具有线程关联性 - 用于窗口的消息在创建并因此拥有该窗口的线程上得到处理.

Using the Win32 APIs, is it possible to create a Window or Dialog in one thread then collect events for it from another thread?

Are HWNDs tied to threads?

Trying the contrived example below I never see GetMessage() fire.

HWND g_hWnd;

DWORD WINAPI myThreadProc(LPVOID lpParam)
{
    while(GetMessage(&msg, hWnd, 0, 0) > 0)
    {
       ...
    }

}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd) 
{
    hWnd = CreateDialog(hInstance, MAKEINTRESOURCE(IDD_MYDIALOG), 0, myDlgProc);
    CreateThread(NULL, 0 myThreadProc, NULL, 0, NULL);
    ...
}

But here, I do.

HWND g_hWnd;
HINSTANCE g_hInstance;

DWORD WINAPI myThreadProc(LPVOID lpParam)
{
    hWnd = CreateDialog(hInstance, MAKEINTRESOURCE(IDD_MYDIALOG), 0, myDlgProc);

    while(GetMessage(&msg, hWnd, 0, 0) > 0)
    {
       ...
    }

}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd) 
{
    g_hInstance = hInstance;
    CreateThread(NULL, 0 myThreadProc, NULL, 0, NULL);
    ...
}

Can somebody explain what I'm seeing?

解决方案

No.

GetMessage returns messages on the current thread's input queue. The HWND parameter is a filter, so that GetMessage only returns messages in the current thread's input queue intended for that window.

Windows have thread affinity - messages intended for a window get handled on the thread that created and therefore owns the window.

相关文章