How to remap keyboard key in c++ with LowLevelKeyb

2019-05-07 10:58发布

问题:

I need to remap some of keys like Left Alt but i just disable it so code for disable Left Alt look like this:

LRESULT CALLBACK LowLevelKeyboardProc(int nCode, WPARAM wParam, LPARAM lParam)
{
    if (nCode == HC_ACTION)
    {
        KBDLLHOOKSTRUCT* p = (KBDLLHOOKSTRUCT*) lParam;
        if (p->vkCode == VK_LMENU) return 1;            
    }
    return CallNextHookEx(hHook, nCode, wParam, lParam);
}

So I try to remap Left Alt to Left Ctrl and use function like keybd_event and SendMessageA but didn't get nothing.

LRESULT CALLBACK LowLevelKeyboardProc(int nCode, WPARAM wParam, LPARAM lParam)
{
    if (nCode == HC_ACTION)
    {
        KBDLLHOOKSTRUCT* p = (KBDLLHOOKSTRUCT*) lParam;
        if (p->vkCode == VK_LMENU)
        {
            keybd_event(VK_CONTROL, 0, 0, 0);
            // or use this is sameSendMessageA(0, WM_KEYUP, VK_CONTROL, 0);
        }   
    }
    return CallNextHookEx(hHook, nCode, wParam, lParam);
}

How to remap Left Alt to Left Ctrl?

回答1:

This is a way to remap Alt to Ctrl works great. Don't forget the default parameter switches back to alt if you do not define wParam may just be my computer well give it a try

include iostream
include windows.h

using namespace std;

HHOOK hHook = 0;

LRESULT CALLBACK LowLevelKeyboardProc(int nCode, WPARAM wParam, LPARAM lParam)
{
    if (nCode == HC_ACTION)
    {
        KBDLLHOOKSTRUCT* p = (KBDLLHOOKSTRUCT*) lParam;
        if (p->vkCode == VK_LMENU) // VK_LMENU = ALT key
        {
           switch (wParam){

            case WM_SYSKEYDOWN :{ // use SYSKEYDOWN
                cout << "Key down" << endl;

                keybd_event(VK_LCONTROL, 0x1D, KEYEVENTF_EXTENDEDKEY | 0, 0 );
            break;
            }
            case WM_KEYUP: // use regular keyup
             {
                cout << "Key up" << endl;

                keybd_event( VK_LCONTROL, 0x1D, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
                return 1;

            break;
             }
            default:
                wParam = WM_SYSKEYDOWN; // if you do not specify it changes back to alt
                break;
           }
            return 1;
        }
    }
    return CallNextHookEx(hHook, nCode, wParam, lParam);
}
int WINAPI WinMain (HINSTANCE hThisInstance, HINSTANCE hPrevInstance, LPSTR lpszArgument, int nCmdShow)
{

   hHook = SetWindowsHookEx(WH_KEYBOARD_LL, &LowLevelKeyboardProc, hThisInstance, NULL);
    if (hHook == NULL)
    {
        cout << "Error" << endl;
        return 1;
    }

    MSG messages;

    while (GetMessage (&messages, NULL, 0, 0))
    {
        TranslateMessage(&messages);
        DispatchMessage(&messages);
    }

    return messages.wParam;
}