消息循环锁定UI线程?

时间:2013-06-23 01:54:43

标签: c++ winforms visual-c++

我正在尝试使用单独的控制线程来加载和运行表单。它部分加载,即表单显示但不是所有控件。然后它变得反应迟钝,我不知道为什么。我已经尝试过我所知道的一切。主线程创建并隐藏窗口,创建UI线程,并将表单事件处理程序发送的消息处理到隐藏窗口。我想我可能有一个紧密的消息处理循环,它会锁定表单,但我不知道如何解决这个问题。

这是主要功能:

int APIENTRY _tWinMain(_In_ HINSTANCE hInstance,
                        _In_opt_ HINSTANCE hPrevInstance,
                        _In_ LPTSTR    lpCmdLine,
                        _In_ int       nCmdShow)
{
    UNREFERENCED_PARAMETER(hPrevInstance);
    UNREFERENCED_PARAMETER(lpCmdLine);

    // TODO: Place code here.
    MSG msg;
    HACCEL hAccelTable;

    bShutdown = FALSE;

    // Initialize global strings
    LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
    LoadString(hInstance, IDC_TURBOCOPY, szWindowClass, MAX_LOADSTRING);
    MyRegisterClass(hInstance);

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

    hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_TURBOCOPY));
    g_UIThread.g_uipUIThread = _beginthread(UIThread, 0, (void *)hWnd);

    // Main message loop:
    while (!bShutdown) {
        if (PeekMessage(&msg, hWnd, 0, 0, PM_NOREMOVE)) {
            if (GetMessage(&msg, hWnd, 0, 0)) {
                if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) {
                    TranslateMessage(&msg);
                    DispatchMessage(&msg);
                }
            }
            else {
                bShutdown = TRUE;
            }
        }
    }

    return (int) msg.wParam;
}

这是UI线程:

void UIThread(void *pvParam)
{
    Main^ hForm = gcnew Main;

    hWnd = (HWND)pvParam;// Get hWnd as destination for messages triggered by form events
    hForm->Show();  // Show the main form

            // Process form events until this thread is terminated
    WaitForSingleObject(g_hUICloseEvent, INFINITE);
}

以下是表单的事件处理程序如何工作(或根据具体情况不起作用)的示例:

System::Void Main::btnCloseCancel_Click(System::Object^  sender, System::EventArgs^  e)
{
    SetEvent(g_hUICloseEvent);
    SendMessage(hWnd, WM_QUIT, NULL, NULL);
}

有谁可以告诉我为什么表单没有响应?我快要放弃了。

感谢。

0 个答案:

没有答案