Windows -- Qt 利用RAWINPUT来获取外设输入

使用RAWINPUT可以查看外设事件的具体信息,具体方法如下:
1.在 构造 函数里添加一下代码:

HWND m_hwnd = this->winId;
RegisitWindow(HWND hwnd);

2.注册RawInput设备
主要是用函数 RegisterRawInputDevice
使用方法如下:

bool Dialog::RegisitWindow(HWND hwnd)
{
    if ( nullptr == hwnd ){
        return FALSE;
    }
    RAWINPUTDEVICE rid;  //设备信息
    rid.usUsagePage = 0x0d;
    rid.usUsage = 0x05; // 0X05 触摸板    06键盘   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
3.重写 nativeEvent 函数
重写nativeEvent可以获取windows的消息循环,注册成功后,消息循环接受 IN_PUT,我们从中获取相关数据

bool Dialog::nativeEvent(const QByteArray &eventType, void *message, long *result)
{
    MSG* msg = (MSG*)message;
    LPBYTE lpb;
    RAWINPUT* raw;
    UINT dwSize;
    if(msg->message == WM_INPUT){
        GetRawInputData((HRAWINPUT)msg->lParam, RID_INPUT, nullptr, &dwSize, sizeof(RAWINPUTHEADER));
        lpb = new BYTE[dwSize];
        if (lpb == nullptr)
            return 0;
        if (GetRawInputData((HRAWINPUT)msg->lParam, RID_INPUT, lpb, &dwSize, sizeof(RAWINPUTHEADER)) != dwSize )
            OutputDebugString (TEXT("GetRawInputData does not return correct size !\n"));
        raw = (RAWINPUT*)lpb;
        if(raw->header.dwType == RIM_TYPEHID){
            DWORD len = raw->data.hid.dwSizeHid;
            int f = (len == 0x23)?raw->data.hid.bRawData[n]:raw->data.hid.bRawData[n];
            qDebug() << f;            
        }
        delete[] lpb;
    }
    return false;
}

上述 bRawData[]bRawData[],是依据具体协议来的

上一篇:《WINDOWS游戏编程之从零开始》第三章学习笔记


下一篇:枚举窗口、鼠标、键盘