How to listen for key stroke outside terminal with C++ on Windows

Viewed 260

I am new to programming, and currently I am using this code to listen for my keystroke:

#include <windows.h>
#include <stdio.h>

int main()
{
    while (1)
    {
        HANDLE hInput = GetStdHandle(STD_INPUT_HANDLE);
        DWORD NumInputs = 0;
        DWORD InputsRead = 0;
        bool running = true;

        INPUT_RECORD irInput;

        GetNumberOfConsoleInputEvents(hInput, &NumInputs);

        ReadConsoleInput(hInput, &irInput, 1, &InputsRead);

        switch (irInput.Event.KeyEvent.wVirtualKeyCode)
        {
        case VK_F1:
            puts("F1");
            break;
        case VK_F2:
            puts("F2");
            break;

        case VK_F3:
            puts("F3");
            break;

        case VK_F4:
            puts("F4");
            break;
        }
    }
}

However, I need an event listener for it even if my terminal doesn't have focus. Is that possible?

1 Answers

You can use SetWindowsHookExA with WH_KEYBOARD_LL.

And set the corresponding hook function for this hook to correspond to the keys you need.

Here is the sample that you can listen the keyboard without focus:

#include <windows.h>
#include <stdio.h>
HHOOK _k_hook;
LRESULT __stdcall k_Callback1(int nCode, WPARAM wParam, LPARAM lParam)
{
    PKBDLLHOOKSTRUCT key = (PKBDLLHOOKSTRUCT)lParam;
    //a key was pressed
    if (wParam == WM_KEYDOWN && nCode == HC_ACTION)
    {
        switch (key->vkCode)
        {
        case VK_F1:
            puts("F1");
            break;
        case VK_F2:
            puts("F2");
            break;

        case VK_F3:
            puts("F3");
            break;

        case VK_F4:
            puts("F4");
            break;
        }
    }

    return CallNextHookEx(NULL, nCode, wParam, lParam);
}


int main()
{
    _k_hook = SetWindowsHookExA(WH_KEYBOARD_LL, k_Callback1, NULL, 0);
    MSG msg;
    while (GetMessage(&msg, NULL, 0, 0) != 0)
    {

    }
    if (_k_hook)
        UnhookWindowsHookEx(_k_hook);
    return TRUE;
}
Related