1,316
社区成员
发帖
与我相关
我的任务
分享
#include <winioctl.h>
#include <setupapi.h>
#include <stdio.h>
#include <tchar.h>
//---------------------------------------------------------------------------
// 用Setup API获取本机的串口设备注册属性列表
BOOL CrnGetComPortList(TStrings *pList)
{
PSP_DEVICE_INTERFACE_DETAIL_DATA pspdidd;
SP_DEVICE_INTERFACE_DATA spdid;
SP_DEVINFO_DATA spdd;
HDEVINFO hDevInfo;
DWORD dwIndex, dwSize, dwType;
TCHAR szMessage[1024], szProperty[256];
ZeroMemory((PVOID)&spdid, sizeof(spdid));
spdid.cbSize = sizeof(spdid);
if(INVALID_HANDLE_VALUE == (hDevInfo =
SetupDiGetClassDevs(&GUID_DEVINTERFACE_COMPORT, NULL,
NULL, DIGCF_DEVICEINTERFACE | DIGCF_PRESENT)))
{
_stprintf(szMessage, TEXT("SetupDiGetClassDevs failed, Error %u"), GetLastError());
MessageBox(0, szMessage, NULL, MB_OK);
return(FALSE);
}
for (dwIndex = 0; (SetupDiEnumDeviceInterfaces(hDevInfo,
NULL, &GUID_DEVINTERFACE_COMPORT, dwIndex, &spdid)); ++dwIndex)
{
dwSize = 0;
SetupDiGetDeviceInterfaceDetail(hDevInfo, &spdid, NULL, 0, &dwSize, NULL);
if (dwSize)
{
if(NULL == (pspdidd =
(PSP_DEVICE_INTERFACE_DETAIL_DATA)HeapAlloc(
GetProcessHeap(), HEAP_ZERO_MEMORY, dwSize)))
continue;
pspdidd->cbSize = sizeof(*pspdidd);
ZeroMemory((PVOID)&spdd, sizeof(spdd));
spdd.cbSize = sizeof(spdd);
if (SetupDiGetDeviceInterfaceDetail(hDevInfo, &spdid,
pspdidd, dwSize, &dwSize, &spdd))
{
if (SetupDiGetDeviceRegistryProperty(hDevInfo, &spdd,
SPDRP_FRIENDLYNAME, &dwType,
(PBYTE)szProperty, sizeof(szProperty), NULL))
{
if (dwType == REG_SZ)
pList->Add(szProperty);
}
}
HeapFree(GetProcessHeap(), 0, (PVOID)pspdidd);
}
}
SetupDiDestroyDeviceInfoList(hDevInfo);
return(TRUE);
}
void __fastcall TForm1::Button1Click(TObject *Sender)
{
CrnGetComPortList(Memo1->Lines);
}