Created
January 8, 2015 06:34
-
-
Save owlsperspective/0c82b19617b3ad5ba15a to your computer and use it in GitHub Desktop.
シリアルポートをフレンドリ名で列挙 (C++)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <windows.h> | |
#include <setupapi.h> | |
#include <System.hpp> | |
void __fastcall GetCommPortsWithName(std::vector<std::pair<int,String> >& CommPorts) | |
{ | |
GUID Guid; | |
DWORD RequiredSize = 0; | |
if (!SetupDiClassGuidsFromName(_TEXT("Ports"),&Guid,1,&RequiredSize)) { | |
RaiseLastOSError(); | |
} | |
HDEVINFO hDevInfo = SetupDiGetClassDevs(&Guid,NULL,NULL,DIGCF_PRESENT); | |
if (hDevInfo == INVALID_HANDLE_VALUE) { | |
RaiseLastOSError(); | |
} | |
__try { | |
for (DWORD index = 0; ; ++index) { | |
SP_DEVINFO_DATA DevInfoData; | |
memset(&DevInfoData,0,sizeof(DevInfoData)); | |
DevInfoData.cbSize = sizeof(DevInfoData); | |
if (!SetupDiEnumDeviceInfo(hDevInfo,index,&DevInfoData)) { | |
break; | |
} | |
DWORD prop = SPDRP_FRIENDLYNAME; | |
SetupDiGetDeviceRegistryProperty(hDevInfo,&DevInfoData,prop,NULL, | |
NULL,0,&RequiredSize); | |
TCHAR *s1 = new TCHAR [(RequiredSize + sizeof(TCHAR)) / sizeof(TCHAR)]; | |
__try { | |
if (SetupDiGetDeviceRegistryProperty(hDevInfo,&DevInfoData,prop,NULL, | |
reinterpret_cast<PBYTE>(s1),RequiredSize,&RequiredSize)) { | |
HKEY hKey = SetupDiOpenDevRegKey(hDevInfo,&DevInfoData,DICS_FLAG_GLOBAL,0,DIREG_DEV,KEY_READ); | |
if (hKey != INVALID_HANDLE_VALUE) { | |
if (RegQueryInfoKey(hKey,NULL,NULL,NULL,NULL,NULL,NULL,NULL, | |
NULL,&RequiredSize,NULL,NULL) == ERROR_SUCCESS) { | |
TCHAR *s2 = new TCHAR [(RequiredSize + sizeof(TCHAR)) / sizeof(TCHAR)]; | |
__try { | |
DWORD regtype; | |
if ((RegQueryValueEx(hKey,_TEXT("PortName"),NULL,®type, | |
reinterpret_cast<PBYTE>(s2),&RequiredSize) == ERROR_SUCCESS) && | |
(regtype == REG_SZ)) { | |
String s(s2); | |
if (s.SubString(0,3).CompareIC(_TEXT("COM")) == 0) { | |
int port; | |
if ((TryStrToInt(s.SubString0(3,s.Length()),port) == true) && (port > 0)) { | |
CommPorts.push_back(std::make_pair(port,s1)); | |
} | |
} | |
} | |
} | |
__finally { | |
delete [] s2; | |
} | |
} | |
RegCloseKey(hKey); | |
} | |
} | |
} | |
__finally { | |
delete [] s1; | |
} | |
} | |
} | |
__finally { | |
SetupDiDestroyDeviceInfoList(hDevInfo); | |
} | |
return; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment