首页 > 解决方案 > WM_CLOSE 消息和应用程序冻结

问题描述

拥有如此超级简单的 Win 应用程序:

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;
    }       

    HACCEL hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_GL1WIN));

    MSG msg;        

    // Main message loop:
    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_COMMAND: {
            int wmId = LOWORD(wParam);
            // Parse the menu selections:
            switch (wmId) {
            case IDM_ABOUT:
                DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
                break;
            case IDM_EXIT:
                DestroyWindow(hWnd);
                break;
            default:
                return DefWindowProc(hWnd, message, wParam, lParam);
            }
        }
        break;          

        case WM_CLOSE:              
            break;

        case WM_DESTROY:                
            PostQuitMessage(0);
            break;

        default:
            return DefWindowProc(hWnd, message, wParam, lParam);
    }

    return 0;

}   

WM_CLOSE案例被禁用(注释掉)时,一切正常 - 当我单击X按钮时,窗口关闭,但是当WM_CLOSE案例像上面的代码一样启用时,应用程序似乎冻结 - 单击按钮时没有反应X,我必须杀死它task manager

标签: c++windowsvisual-studio

解决方案


在 WM_CLOSE 上,窗口通常应该用 销毁DestroyWindow,例如:

 case WM_CLOSE:   
            DestroyWindow(hWnd);
            break;

在您的情况下,您只需返回而不对该窗口执行任何操作,因此它很简单“冻结”。


推荐阅读