VC 搜索本地可用串口
最簡單的方法:枚舉
複雜一點的辦法:參考驅動開發,查看系統設備的符號表。
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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.