Search code examples
c++windowswinapisystem-tray

How to hide a window, instead of exiting, when the top right cross button is pressed?


By default, a standard window created with:

HWND hwnd = CreateWindowEx(0, CLASS_NAME, L"Test", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, hInstance, NULL);
ShowWindow(hwnd, nCmdShow);

will be closed, causing the program to exit, when we click on the top right cross:

enter image description here

My program has a single such window, but also an always-present icon in the system tray notification area.

How to make that clicking on the top right cross makes this window hidden, but does not exit the program?

This didn't work in the main window message loop, the app is still exiting.

switch (msg) 
{
    case WM_CLOSE:
        ShowWindow(hWnd, SW_HIDE);
        break;
}

Solution

  • DefWindowProc calls DestroyWindow when it gets WM_CLOSE so all you have to do is not pass the message to DefWindowProc:

    switch (msg) 
    {
        case WM_CLOSE:
            ShowWindow(hWnd, SW_HIDE);
            return 0;
    }
    

    DestroyWindow alone will not exit a program with a "normal" message loop. It is usually the WM_QUIT message you generate in your main windows WM_DESTROY with PostQuitMessage that causes your message loop to stop and exit the program...