如何使用LowLevelKeyboardProc在c ++中重新映射键盘键?

时间:2013-07-02 07:12:03

标签: c++ windows keyboard shortcut remap

我需要重新映射一些键,例如Left Alt ,但我只是禁用它,因此禁用Left Alt 的代码如下所示:

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

所以我尝试将Left Alt 重新映射到Left Ctrl 并使用keybd_eventSendMessageA之类的函数,但没有得到任何结果。< / p>

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

如何将左 Alt 重新映射到左 Ctrl

1 个答案:

答案 0 :(得分:7)

这是一种将 Alt 重新映射到 Ctrl 的方法。不要忘记默认参数 如果你没有定义wParam,那么切换回alt可能只是我的电脑试一试

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