Windows线程同时运行多次

时间:2017-12-29 02:56:12

标签: c++ windows multithreading winapi

为了简化这种情况,我编辑了Visual Studio New Projects / Visual C ++ / Windows Desktop / Windows桌面应用程序中的代码。只需添加RegisterHotKey中的case WM_HOTKEYhWnd_Main以及InitInstance

当我按Shift+Ctrl+Alt+Win+Z时,MessageBox会出现多次。我认为消息框将阻止消息循环线程(即Visual Studio线程窗口中的MainThread),第二次按Shift+Ctrl+Alt+Win+Z时,应在消息队列中等待消息WM_HOTKEY。单个线程如何同时运行多次?我的理解错了吗?

如何只限制MessageBox(hWnd_Main, _T("Test2"), _T("Test2"), NULL);的一个条目?我在消息框之后打开一个文件,发现它可以打开多次。

int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
    _In_opt_ HINSTANCE hPrevInstance,
    _In_ LPWSTR    lpCmdLine,
    _In_ int       nCmdShow)
{
    MyRegisterClass(hInstance);

    // Perform application initialization:
    if (!InitInstance(hInstance, nCmdShow))
    {
        return FALSE;
    }

    RegisterHotKey(hWnd_Main, 0x666, MOD_ALT | MOD_CONTROL | MOD_SHIFT | MOD_WIN, 'Z');

    MSG msg;

    while (GetMessage(&msg, nullptr, 0, 0))
    {
        if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
        {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }
    }

    return (int)msg.wParam;
}

LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    switch (message)
    {
    case WM_HOTKEY:
    {
        UINT nID = LOWORD(wParam);
        if (nID == 0x666)
        {
            printf("GetCurrentThreadId: %d\n",GetCurrentThreadId());
            MessageBox(hWnd_Main, _T("Test"), _T("Test"), NULL);
            MessageBox(hWnd_Main, _T("Test2"), _T("Test2"), NULL);
        }
    }
        break;
    case WM_DESTROY:
        PostQuitMessage(0);
        break;
    default:
        return DefWindowProc(hWnd, message, wParam, lParam);
    }
    return 0;
}

0 个答案:

没有答案