Search code examples
c++winapivisual-c++keyboardkeypress

Detect (and override) keypress of F1 key even if another app has focus


How is it possible, in a Win32 application coded in Visual C++, to detect the keypress of the F1 key and restore/maximize its GUI when this happens?

This key should be detected even if another application has focus, and override the usual F1 "help" window behaviour.

int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE, PWSTR pCmdLine, int nCmdShow)
{
    const wchar_t CLASS_NAME[]  = L"Test";
    WNDCLASS wc = { };
    wc.lpfnWndProc   = WindowProc;
    wc.hInstance     = hInstance;
    wc.lpszClassName = CLASS_NAME;
    RegisterClass(&wc);

    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);
    MSG msg = { };
    while (GetMessage(&msg, NULL, 0, 0))
    {

        // Should it be detected here ? //

        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
    return 0;
}

Solution

  • As mentioned in a comment by @RbMm, the solution is:

    int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE, PWSTR pCmdLine, int nCmdShow)
    {
        const wchar_t CLASS_NAME[]  = L"Test";
        WNDCLASS wc = { };
        wc.lpfnWndProc   = WindowProc;
        wc.hInstance     = hInstance;
        wc.lpszClassName = CLASS_NAME;
        RegisterClass(&wc);
    
        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);
    
        RegisterHotKey(hWnd, 100, 0, VK_F1);  // here we go!
    
        MSG msg = { };
        while (GetMessage(&msg, NULL, 0, 0))
        {
            if (msg.message == WM_HOTKEY)
                // Do something here
    
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }
        return 0;
    }
    

    See also here.