捕获鼠标和键盘的原始数据

时间:2021-08-21 10:51:05
为了实现局域网内鼠标键盘的共享(比如你同时用两台电脑,这时就希望能共享鼠标和键盘),需要获得主机的鼠标键盘原始信息,下面的demo演示了如何获得主机的鼠标键盘原始数据。程序运行后无论是否获得焦点,都能够得到鼠标键盘数据。

实现的关键是使用了RawInput,使用过程是先注册需要捕获的设备,然后在DefWindowProc函数中截取所需的数据。

其中注册鼠标键盘设备的代码放在一个按钮的响应函数中:

void CRawInputDlg::OnButton1() 
{
RAWINPUTDEVICE Rid[2];

Rid[0].usUsagePage = 0x01;
Rid[0].usUsage = 0x02;
Rid[0].dwFlags = RIDEV_INPUTSINK; // adds HID mouse and also ignores legacy mouse messages RIDEV_NOLEGACY RIDEV_INPUTSINK
Rid[0].hwndTarget = m_hWnd;

Rid[1].usUsagePage = 0x01;
Rid[1].usUsage = 0x06;
Rid[1].dwFlags = RIDEV_INPUTSINK; // adds HID keyboard and also ignores legacy keyboard messages RIDEV_NOLEGACY RIDEV_INPUTSINK
Rid[1].hwndTarget = m_hWnd;

if (RegisterRawInputDevices(Rid, 2, sizeof(Rid[0])) == FALSE) {
//registration failed. Call GetLastError for the cause of the error
MessageBox("错误的注册信息");
}


}

数据捕获:

LRESULT CRawInputDlg::DefWindowProc(UINT message, WPARAM wParam, LPARAM lParam) 
{
// TODO: Add your specialized code here and/or call the base class
if ( message == WM_INPUT )
{
UINT dwSize=0;
GetRawInputData(
(HRAWINPUT)lParam,
(UINT)RID_INPUT,
(LPVOID)NULL,
(PUINT) &dwSize,
(UINT)sizeof(RAWINPUTHEADER)
);

LPBYTE lpbBuffer = new BYTE[dwSize];

GetRawInputData(
(HRAWINPUT)lParam,
(UINT)RID_INPUT,
(LPVOID)lpbBuffer,
(PUINT)&dwSize,
(UINT)sizeof(RAWINPUTHEADER)
);

RAWINPUT * raw = (RAWINPUT *) lpbBuffer;

CString strTemp;

tmTime=CTime::GetCurrentTime();
CString strT;
strT=tmTime.Format("%H:%M:%S");

if (raw->header.dwType == RIM_TYPEMOUSE)
{
strTemp.Format(" 鼠标: BtnState=%04x deltaX=%d deltaY=%d\r\n",
raw->data.mouse.ulButtons,
raw->data.mouse.lLastX,
raw->data.mouse.lLastY
);

strTemp=strT+strTemp;
DisplayData(strTemp);

delete[] lpbBuffer;

return TRUE;
}
else if(raw->header.dwType == RIM_TYPEKEYBOARD){
strTemp.Format(" 键盘:make=%04x Flags:%04x msg=%04x VK=%c",
raw->data.keyboard.MakeCode,
raw->data.keyboard.Flags,
raw->data.keyboard.Message,
raw->data.keyboard.VKey
);

strTemp=strT+strTemp;
DisplayData(strTemp);

delete[] lpbBuffer;

return TRUE;
}
}
return CDialog::DefWindowProc(message, wParam, lParam);
}

运行效果

捕获鼠标和键盘的原始数据

参考资料:

http://bbs.csdn.net/topics/330017277

Using Raw Input
http://msdn.microsoft.com/en-us/library/ms645546(v=vs.85).aspx
Using Mouse Input
msdn.microsoft.com/en-us/library/ms645602(v=vs.85).aspx
About Raw Input
http://msdn.microsoft.com/en-us/library/ms645543(v=vs.85).aspx