RegisterRawInputDevices 可以注册鼠标或者键盘等输入的信息,然后GetRawInputData可以获取传来的WM_INPUT消息中的输入信息。
代码参考:
#include <windows.h> #include <iostream> using namespace std; LRESULT CALLBACK WindProc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam) { if (Msg == WM_INPUT) { HRAWINPUT hRawInput = (HRAWINPUT)lParam; RAWINPUT input = { 0 }; UINT size = sizeof(input); GetRawInputData(hRawInput, RID_INPUT, &input, &size, sizeof(RAWINPUTHEADER)); printf("vkey: %x, flag: %d ", input.data.keyboard.VKey, input.data.keyboard.Flags); } return DefWindowProc(hWnd, Msg, wParam, lParam); } int main() { WNDCLASSEX wcx = { 0 }; wcx.cbSize = sizeof(WNDCLASSEX); wcx.lpfnWndProc = WindProc; wcx.hInstance = GetModuleHandle(NULL); wcx.lpszClassName = TEXT("RawInputClass"); RegisterClassEx(&wcx); HWND hWnd = CreateWindowEx(0, TEXT("RawInputClass"), NULL, 0, 0, 0, 0, 0, HWND_MESSAGE, NULL, GetModuleHandle(NULL), NULL); RAWINPUTDEVICE rid = { 0 }; rid.usUsagePage = 0x01; rid.usUsage = 0x06; //keyboard rid.dwFlags = RIDEV_INPUTSINK; rid.hwndTarget = hWnd; RegisterRawInputDevices(&rid, 1, sizeof(RAWINPUTDEVICE)); MSG msg; while (GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } return 0; }