使用函数RegisterHotKey,其原型为:
BOOL RegisterHotKey(
HWND hWnd, int id, UINT fsModifiers, UINT vk );
Parameters
- hWnd
- [in] Handle to the window that will receive messages generated by the hot key. If this parameter is NULL, WM_HOTKEY messages are posted to the message queue of the calling thread and must be processed in the message loop.
- id
- [in] Specifies the identifier of the hot key. No other hot key in the calling thread should have the same identifier. An application must specify a value in the range 0x0000 through 0xBFFF. A shared dynamic-link library (DLL) must specify a value in the range 0xC000 through 0xFFFF (the range returned by the function). To avoid conflicts with hot-key identifiers defined by other shared DLLs, a DLL should use the GlobalAddAtom function to obtain the hot-key identifier.
- fsModifiers
- [in] Specifies keys that must be pressed in combination with the key specified by the uVirtKey parameter in order to generate the WM_HOTKEY message. The fsModifiers parameter can be a combination of the following values.
- MOD_ALT
- Either ALT key must be held down.
- MOD_CONTROL
- Either CTRL key must be held down.
- MOD_SHIFT
- Either SHIFT key must be held down.
- MOD_WIN
- Either WINDOWS key was held down. These keys are labeled with the Microsoft® Windows® logo.
- vk
- [in] Specifies the virtual-key code of the hot key.
使用方法:
如要为一对话框程序注册热键Ctrl+Alt+K
1、在MyDlg.h中 声明消息映射函数 afx_msg LRESULT OnHotKey(WPARAM wParam,LPARAM lParam);
2、在MyDlg.cpp中,定义消息映射
BEGIN_MESSAGE_MAP(CMyDlg, CDialog)
//{{AFX_MSG_MAP(CMyDlg)
...
ON_MESSAGE(WM_HOTKEY,OnHotKey)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
3、定义消息映射函数
LRESULT CMyDlg::OnHotKey(WPARAM wParam,LPARAM lParam)
{
if (wParam == 6789) //6789为调用RegisterHotKey时指定的热键对应的id
{
AfxMessageBox("you pressed hotkey");
}
return 0;
}
4、在合适的地方调用RegisterHotKey
RegisterHotKey(GetSafeHwnd(),6789,MOD_ALT|MOD_CONTROL,'K');