溫馨提示×

C++ RegisterHotKey怎么使用

c++
小億
135
2023-10-19 09:50:33
欄目: 編程語言

要使用C++中的RegisterHotKey函數(shù),你需要包含windows.h頭文件,并調(diào)用RegisterHotKey函數(shù),該函數(shù)接受三個參數(shù):窗口句柄、熱鍵ID和熱鍵組合。

下面是一個使用RegisterHotKey函數(shù)注冊Ctrl + F1熱鍵的示例:

#include <iostream>
#include <Windows.h>
int main()
{
HWND hwnd = GetConsoleWindow();  // 獲取控制臺窗口句柄
if (!RegisterHotKey(hwnd, 1, MOD_CONTROL, VK_F1))
{
std::cout << "熱鍵注冊失?。?quot; << std::endl;
}
MSG msg = { 0 };
while (GetMessage(&msg, NULL, 0, 0) != 0)
{
if (msg.message == WM_HOTKEY)
{
std::cout << "熱鍵被觸發(fā)!" << std::endl;
}
}
UnregisterHotKey(hwnd, 1);  // 注銷熱鍵
return 0;
}

在上述示例中,我們首先獲取控制臺窗口句柄,然后調(diào)用RegisterHotKey函數(shù)注冊Ctrl + F1熱鍵(熱鍵ID為1)。如果注冊失敗,將輸出錯誤信息。接下來,我們使用GetMessage函數(shù)循環(huán)獲取消息,在消息循環(huán)中判斷是否有WM_HOTKEY消息觸發(fā),如果有,則輸出熱鍵被觸發(fā)的信息。最后,我們使用UnregisterHotKey函數(shù)注銷熱鍵。

0