最简单的方法:枚举
复杂一点的办法:参考驱动开发,查看系统设备的符号表。
typedef struct tagPT_PortsArry
{
int nPortIndex[256];
bool bEnable[256];
}PT_PortsArry, far *LPT_PortsArry;
//------------------------------------------------------------------------------------------------
int QueryComPorts(LPT_PortsArry ptPortsArry)
{
HANDLE hCom;
char cPortName[128];
int i;
int nPortsCount = 0;//串口个数
if (ptPortsArry == NULL)
return -1;
for (i = 1; i <= 256; i ++)
{
sprintf (cPortName, "COM%d", i);
hCom = CreateFile (cPortName, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
ptPortsArry.nPortIndex[i - 1] = i;
if (hCom == INVALID_HANDLE_VALUE)
{
ptPortsArry.bEnable[i - 1] = FALSE;
}
else
{
ptPortsArry.bEnable[i - 1] = TRUE;
CloseHandle (hCom);
nPortsCount ++;
}
}
return nPortsCount;
}
复杂一点的办法:参考驱动开发,查看系统设备的符号表。
typedef struct tagPT_PortsArry
{
int nPortIndex[256];
bool bEnable[256];
}PT_PortsArry, far *LPT_PortsArry;
//------------------------------------------------------------------------------------------------
int QueryComPorts(LPT_PortsArry ptPortsArry)
{
HANDLE hCom;
char cPortName[128];
int i;
int nPortsCount = 0;//串口个数
if (ptPortsArry == NULL)
return -1;
for (i = 1; i <= 256; i ++)
{
sprintf (cPortName, "COM%d", i);
hCom = CreateFile (cPortName, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
ptPortsArry.nPortIndex[i - 1] = i;
if (hCom == INVALID_HANDLE_VALUE)
{
ptPortsArry.bEnable[i - 1] = FALSE;
}
else
{
ptPortsArry.bEnable[i - 1] = TRUE;
CloseHandle (hCom);
nPortsCount ++;
}
}
return nPortsCount;
}