使用RawInput可以查看外设输入事件的具体信息,以区分键盘信息为例:
1.注册RawInput设备
注册主要是RegisterRawInputDevices函数
使用方法如下:
使用RawInput可以区分外设输入事件的具体信息,以区分键盘信息为例:
BOOL MainWindow::RegisitKeyBord(HWND hwnd)
{
if ( NULL == hwnd )
{
return FALSE;
}
RAWINPUTDEVICE rid; //设备信息
rid.usUsagePage = 0x01;
rid.usUsage = 0x06; //键盘 rid.usUsagePage = 0x01; rid.usUsage = 0x02; 为鼠标
rid.dwFlags = RIDEV_INPUTSINK;
rid.hwndTarget = hwnd;
if ( !RegisterRawInputDevices( &rid, 1, sizeof(RAWINPUTDEVICE) ))
{
return FALSE;
}
return TRUE;
}
将窗口句柄和RawInput注册在一起,如果不指定窗口和Flag则只有焦点在窗体时有效
具体参考Windows文档:
https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-registerrawinputdevices
https://docs.microsoft.com/en-us/windows/win32/api/winuser/ns-winuser-rawinputdevice
2.重写nativeEvent函数
由于Qt对Windows下消息循环进行封装,所以我们重写nativeEvent方法以获取消息循环, 注册成功之后,消息循环会开始接收WM_INPUT消息, 我们从中获取输入信息
bool MainWindow::nativeEvent(const QByteArray &eventType, void *message, long *result)
{
MSG *pMSG = ( MSG *)message;
switch (pMSG->message)
{
case WM_INPUT:
{
UINT dwSize;
GetRawInputData((HRAWINPUT)pMSG->lParam, RID_INPUT, NULL, &dwSize, sizeof(RAWINPUTHEADER)); //先获取数据大小dwSize
LPBYTE lpb = new BYTE[dwSize]; //根据大小 创建
if (GetRawInputData((HRAWINPUT)pMSG->lParam, RID_INPUT, lpb, &dwSize, sizeof(RAWINPUTHEADER)) != dwSize) //获取消息信息
{
break;
}
RAWINPUT *raw = (RAWINPUT*)lpb;
if ( raw->header.dwType == RIM_TYPEKEYBOARD && raw->data.keyboard.Flags == RI_KEY_MAKE ) //注释掉的部分 用来判断 按键是否是按下
{
// 消息处理函数
qDebug() << "Key = " << raw->data.keyboard.VKey;
qDebug() << "MakeCode = " << raw->data.keyboard.MakeCode;
qDebug() << "Flags = " << raw->data.keyboard.Flags;
qDebug() << "Message = " << raw->data.keyboard.Message;
qDebug() << "ExtraInformation = " << raw->data.keyboard.ExtraInformation;
qDebug() << "ID = " <<raw->header.hDevice;
}
delete[] lpb;
return 0;
}
}
return QMainWindow::nativeEvent( eventType, message, result);
}
参考:
https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getrawinputdata
至此, 可以打印出获取到的键盘输入信息,每按下一个键就有信息输出