- Published on
Getting the Port Number of a Specific Device from Device Manager
- Authors

- Name
- Daisuke Kobayashi
- https://twitter.com
This is a sample for getting the port number of a specific device shown in Windows Device Manager.
Recently I have been building a program to control a Camera Link camera. Image acquisition is handled through MIL, but camera parameter settings are done over RS-232C. To connect to the camera over 232C, I wanted to retrieve the port number from the board, so I wrote the program below.
#include <iostream>
#include <string>
#include <vector>
#include <windows.h>
#include <setupapi.h>
#pragma comment(lib,"setupapi.lib")
typedef std::basic_string<TCHAR> tstring;
bool ListDevice(const GUID& guid, std::vector<tstring>& devices)
{
SP_DEVINFO_DATA devInfoData;
ZeroMemory(&devInfoData, sizeof(devInfoData));
devInfoData.cbSize = sizeof(devInfoData);
int nDevice = 0;
std::vector<tstring> tmp;
HDEVINFO hDeviceInfo = SetupDiGetClassDevs(&guid, 0, 0, DIGCF_PRESENT |
DIGCF_DEVICEINTERFACE);
while (SetupDiEnumDeviceInfo(hDeviceInfo, nDevice++, &devInfoData)) {
BYTE friendly_name[300];
SetupDiGetDeviceRegistryProperty(hDeviceInfo, &devInfoData,
SPDRP_FRIENDLYNAME, NULL, friendly_name,
sizeof(friendly_name), NULL);
tmp.push_back(tstring((TCHAR*)friendly_name));
}
SetupDiDestroyDeviceInfoList(hDeviceInfo);
devices.swap(tmp);
return true;
}
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
PSTR szCmdLine, int iCmdShow)
{
std::vector<tstring> dev;
ListDevice(GUID_DEVINTERFACE_COMPORT, dev);
for (int i = 0; i < dev.size(); i++) {
MessageBox(NULL, dev[i].c_str(), NULL, IDOK);
if (dev[i].find(TEXT("Matrox")) != tstring::npos) {
int start = dev[i].find(TEXT("("));
int end = dev[i].find(TEXT(")"));
MessageBox(NULL, dev[i].substr(start + 1, end - (start + 1)).c_str(), NULL, IDOK);
}
}
return 0;
}
You can retrieve different information from Device Manager by changing the GUID passed as an argument. This example gets the friendly name shown in Device Manager, but if you want different information, change the third argument to SetupDiGetDeviceRegistryProperty.