|
#include <windows.h>
#include <iostream>
bool IsMouseConnected() {
UINT deviceCount = 0;
if (GetRawInputDeviceList(NULL, &deviceCount, sizeof(RAWINPUTDEVICELIST)) != 0) {
std::cerr << "无法获取设备列表" << std::endl;
return false;
}
PRAWINPUTDEVICELIST pRawInputDeviceList = new RAWINPUTDEVICELIST[deviceCount];
if (GetRawInputDeviceList(pRawInputDeviceList, &deviceCount, sizeof(RAWINPUTDEVICELIST)) == (UINT)-1) {
delete[] pRawInputDeviceList;
std::cerr << "无法获取设备列表" << std::endl;
return false;
}
for (UINT i = 0; i < deviceCount; ++i) {
HANDLE hDevice = pRawInputDeviceList[i].hDevice;
RID_DEVICE_INFO ridDeviceInfo;
ridDeviceInfo.cbSize = sizeof(RID_DEVICE_INFO);
UINT pcbSize = ridDeviceInfo.cbSize;
if (GetRawInputDeviceInfo(hDevice, RIDI_DEVICEINFO, &ridDeviceInfo, &pcbSize) == (UINT)-1) {
continue;
}
if (ridDeviceInfo.dwType == RIM_TYPEMOUSE) {
delete[] pRawInputDeviceList;
return true;
}
}
delete[] pRawInputDeviceList;
return false;
}
bool IsKeyboardConnected() {
UINT deviceCount = 0;
if (GetRawInputDeviceList(NULL, &deviceCount, sizeof(RAWINPUTDEVICELIST)) != 0) {
std::cerr << "无法获取设备列表" << std::endl;
return false;
}
PRAWINPUTDEVICELIST pRawInputDeviceList = new RAWINPUTDEVICELIST[deviceCount];
if (GetRawInputDeviceList(pRawInputDeviceList, &deviceCount, sizeof(RAWINPUTDEVICELIST)) == (UINT)-1) {
delete[] pRawInputDeviceList;
std::cerr << "无法获取设备列表" << std::endl;
return false;
}
for (UINT i = 0; i < deviceCount; ++i) {
HANDLE hDevice = pRawInputDeviceList[i].hDevice;
RID_DEVICE_INFO ridDeviceInfo;
ridDeviceInfo.cbSize = sizeof(RID_DEVICE_INFO);
UINT pcbSize = ridDeviceInfo.cbSize;
if (GetRawInputDeviceInfo(hDevice, RIDI_DEVICEINFO, &ridDeviceInfo, &pcbSize) == (UINT)-1) {
continue;
}
if (ridDeviceInfo.dwType == RIM_TYPEKEYBOARD) {
delete[] pRawInputDeviceList;
return true;
}
}
delete[] pRawInputDeviceList;
return false;
}
int main() {
if (IsMouseConnected()) {
std::cout << "鼠标已插入" << std::endl;
} else {
std::cout << "鼠标未插入" << std::endl;
}
if (IsKeyboardConnected()) {
std::cout << "键盘已插入" << std::endl;
} else {
std::cout << "键盘未插入" << std::endl;
}
return 0;
}
|
|