用C++编写发现手机接入电脑的程序
时间: 2023-08-28 14:05:16 浏览: 60
以下是一个简单的示例程序,可以检测到手机是否连接到计算机,并在连接时打印消息。这个程序使用了Windows API。
```cpp
#include <Windows.h>
int main()
{
// 获取设备接口信息
HDEVINFO deviceInfoSet = SetupDiGetClassDevsA(NULL, "USB", NULL, DIGCF_PRESENT | DIGCF_ALLCLASSES);
if (deviceInfoSet == INVALID_HANDLE_VALUE)
{
printf("Failed to get device info!\n");
return 1;
}
// 枚举设备接口
SP_DEVINFO_DATA deviceInfoData = { 0 };
deviceInfoData.cbSize = sizeof(deviceInfoData);
for (DWORD i = 0; SetupDiEnumDeviceInfo(deviceInfoSet, i, &deviceInfoData); i++)
{
// 获取设备描述符
char buffer[MAX_PATH] = { 0 };
if (!SetupDiGetDeviceRegistryPropertyA(deviceInfoSet, &deviceInfoData, SPDRP_DEVICEDESC, NULL, (PBYTE)buffer, sizeof(buffer), NULL))
{
continue;
}
// 检查设备描述符是否包含手机关键字
if (strstr(buffer, "Mobile") || strstr(buffer, "Android"))
{
printf("Phone connected!\n");
break;
}
}
SetupDiDestroyDeviceInfoList(deviceInfoSet);
return 0;
}
```
请注意,这只是一个简单的示例,可能无法检测所有手机连接情况。如果您需要检测更多设备,请考虑使用更专业的设备管理库。