对于C++应用程序来说,如果焦点不在应用程序,则无法使用键盘对应用程序进行控制。
如果有相关应用,要求焦点不在应用程序也能实现控制时,可以使用windows提供的API,注册系统级快捷键。
BOOL RegisterHotKey(
HWND hWnd,
int id,
UINT fsModifiers,
UINT vk
);
#include "stdafx.h"
int _cdecl _tmain (
int argc,
TCHAR *argv[])
{
if (RegisterHotKey(
NULL,
1,
MOD_ALT | MOD_NOREPEAT,
0x42)) //0x42 is 'b'
{
_tprintf(_T("Hotkey 'ALT+b' registered, using MOD_NOREPEAT flag\n"));
}
MSG msg = {0};
while (GetMessage(&msg, NULL, 0, 0) != 0)
{
if (msg.message == WM_HOTKEY)
{
_tprintf(_T("WM_HOTKEY received\n"));
}
}
return 0;
}
[参考]
[1] https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-registerhotkey