如何捕获CTRL + SPACE + SPACE按键

时间:2013-10-31 10:52:13

标签: c++ win32gui

我如何捕捉用户按“ctrl + space + space”!!!

我使用以下代码成功测试了“ctrl + space”:

RegisterHotKey(0, 1, MOD_CONTROL, VK_SPACE);

2 个答案:

答案 0 :(得分:5)

传统上写的是Ctrl+Space, Space。也就是说,按 Ctrl + Space ,然后按 Space

首先,RegisterHotKey是系统范围的。如果您只想在应用程序中使用多级键盘快捷键,则不应使用RegisterHotKey。

其次,使用RegisterHotKey无法执行此操作,您必须通过以下方式处理两级热键:

  • 在某处设置变量,表示多级热键已经开始,以及它是什么。
  • 编写全局键盘钩子,执行以下操作

    • 检查热键是否已经开始,如果没有则检查是否正常,否则
    • 检查热键的后半部分。如果匹配,请执行正确的操作。
    • 是否匹配,取消"热键等待"状态。

您只能在按下热键时注册键盘挂钩,然后取消注册,或者将其保留在整个时间。

答案 1 :(得分:0)

在点击空格键时使用GetAsyncKeyState(VK_CONTROL)捕获CTRL ..

if (GetAsyncKeyState(VK_CONTROL) !=0 && key == VK_SPACE )
    {
       MessageBox(NULL, "CTRL-SPACE was pressed\nDo something in here", 
       "H O T K E Y", MB_OK);
       CTRL_key=0;
    }

完整代码以捕获CTRL-SPACE:

#define _WIN32_WINNT 0x0400
#pragma comment( lib, "user32.lib" )

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

HHOOK hKeyboardHook;

__declspec(dllexport) LRESULT CALLBACK KeyboardEvent (int nCode, WPARAM wParam, LPARAM lParam)
{
    DWORD SHIFT_key=0;
    DWORD CTRL_key=0;
    DWORD ALT_key=0;

    if  ((nCode == HC_ACTION) &&   ((wParam == WM_SYSKEYDOWN) ||  (wParam == WM_KEYDOWN)))
    {
        KBDLLHOOKSTRUCT hooked_key =    *((KBDLLHOOKSTRUCT*)lParam);
        DWORD dwMsg = 1;
        dwMsg += hooked_key.scanCode << 16;
        dwMsg += hooked_key.flags << 24;
        char lpszKeyName[1024] = {0};
        lpszKeyName[0] = '[';

        int i = GetKeyNameText(dwMsg,   (lpszKeyName+1),0xFF) + 1;
        lpszKeyName[i] = ']';

        int key = hooked_key.vkCode;

        SHIFT_key = GetAsyncKeyState(VK_SHIFT);
        CTRL_key = GetAsyncKeyState(VK_CONTROL);
        ALT_key = GetAsyncKeyState(VK_MENU);


        if (GetAsyncKeyState(VK_CONTROL) !=0 && key == VK_SPACE )
            {
               MessageBox(NULL, "CTRL-SPACE was pressed\nDo something in here", "H O T K E Y", MB_OK);
               CTRL_key=0;
            }



        printf("lpszKeyName = %s\n",  lpszKeyName );
    }
    return CallNextHookEx(hKeyboardHook,    nCode,wParam,lParam);
}

void MessageLoop()
{
    MSG message;
    while (GetMessage(&message,NULL,0,0))
    {
        TranslateMessage( &message );
        DispatchMessage( &message );
    }
}

DWORD WINAPI my_HotKey(LPVOID lpParm)
{
    HINSTANCE hInstance = GetModuleHandle(NULL);
    if (!hInstance) hInstance = LoadLibrary((LPCSTR) lpParm);
    if (!hInstance) return 1;

    hKeyboardHook = SetWindowsHookEx (  WH_KEYBOARD_LL, (HOOKPROC) KeyboardEvent,   hInstance,  NULL    );
    MessageLoop();
    UnhookWindowsHookEx(hKeyboardHook);
    return 0;
}

int main(int argc, char** argv)
{
    HANDLE hThread;
    DWORD dwThread;

    hThread = CreateThread(NULL,NULL,(LPTHREAD_START_ROUTINE)   my_HotKey, (LPVOID) argv[0], NULL, &dwThread);

    //ShowWindow(FindWindowA("ConsoleWindowClass", NULL), false);

    if (hThread) return WaitForSingleObject(hThread,INFINITE);
    else return 1;

}