多少年了,现成的定义系统热键的API,我却不知道 RegisterHotKey() 与 UnregisterHotKey()
多少年了,尽然不知道定义一个系统热键是如此的简单:RegisterHotKey() 与 UnregisterHotKey()
char keys[3] = {'H', 'J', 'G'}; //可选的三个键 int n; for(n = 0; n < 3; n++) { //定义一个系统范围的热键 //若函数调用成功,返回一个非0值。若函数调用失败,则返回值为0。 //参考: https://bbs.csdn.net/topics/392280021?page=1 与 https://ask.csdn.net/questions/273724?sort=id int status = RegisterHotKey(hwnd, id_b_location_and_color_static, MOD_CONTROL | MOD_ALT, keys[n]); printf("status:%d\n", status); if(status) { char szTip[32]; sprintf(szTip, "快捷键: Ctrl + Alt + %c", keys[n] + 32); // + 32, 表示将大写字母转换成小写字母 setToolTip(hwnd_b_location_and_color_static, szTip, hInstance); //设置提示 break; } else { //printf("系统热键定义失败, 可能与其他软件冲突。\n"); } }
接收系统热键消息:
LRESULT CALLBACK WindowProcedure (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) /* handle the messages */ { case WM_HOTKEY: //按下【系统热键】 { //参考: https://bbs.csdn.net/topics/392280021?page=1 与 https://ask.csdn.net/questions/273724?sort=id #define _use_wParam //使用 wParam 来判断: https://docs.microsoft.com/en-us/windows/win32/inputdev/wm-hotkey #ifdef _use_wParam //printf("按下系统热键\n"); if(wParam == id_b_location_and_color_static) { //释放调用线程先前登记的热键 //若函数调用成功,返回值不为0。若函数调用失败,返回值为0 //int status = UnregisterHotKey(hwnd, id_b_location_and_color_static); //printf("status2:%d\n", status); if(IsWindowEnabled(hwnd_b_location_and_color_static)) //当【按钮】可用状态时 { SendMessage(hwnd, WM_COMMAND, MAKELPARAM(id_b_location_and_color_static, 0), 0); //触发事件 } } #else UINT fuModifiers = (UINT)LOWORD(lParam); UINT uVirtKey = (UINT)HIWORD(lParam); switch (fuModifiers) { case MOD_CONTROL | MOD_ALT: { switch (uVirtKey) { case 'H': // Ctrl + Alt + h { //printf("Ctrl + Alt + h\n"); //释放调用线程先前登记的热键 //若函数调用成功,返回值不为0。若函数调用失败,返回值为0 //int status = UnregisterHotKey(hwnd, id_b_location_and_color_static); //printf("status2:%d\n", status); if(IsWindowEnabled(hwnd_b_location_and_color_static)) //当【按钮】可用状态时 { SendMessage(hwnd, WM_COMMAND, MAKELPARAM(id_b_location_and_color_static, 0), 0); //触发事件 } break; } } break; } } #endif // _use_wParam break; }