列举本机串口(含虚拟串口)

来源:互联网 发布:激战2马乔丽捏脸数据 编辑:程序博客网 时间:2024/04/30 22:10

第一种 枚举注册表

void  GetPortList(char **lpPortlist,int& count){    HKEY hKey;    LONG lRes = RegOpenKey( HKEY_LOCAL_MACHINE, "HARDWARE\\DEVICEMAP\\SERIALCOMM",        &hKey );    assert( lRes == ERROR_SUCCESS );    bool bGetCount=false;    if(count==0)    bGetCount=true;    else    count=0;    for( int i = 0; 1; ++i )    {        char szName[MAX_PATH]="";        unsigned char szValue[MAX_PATH]="";        DWORD sizeName=100, sizeValue=100, type=0;        lRes = RegEnumValue( hKey, i, szName, &sizeName, NULL, &type, szValue, &sizeValue );                if( lRes != ERROR_SUCCESS )            break;        if(!bGetCount)        {          memset(lpPortlist[i],0,MAX_PATH);          memcpy(lpPortlist[i],szValue,MAX_PATH);        }        ++count;    }    RegCloseKey( hKey );}调用示例:char *pszPorts[MAX_PATH]={0};  int count=0;  GetPortList(NULL,count);  for(int i=0;i<count;++i)  {    pszPorts[i]=new char[MAX_PATH];    assert(pszPorts[i]!=NULL);  }  GetPortList(pszPorts,count);  for(int i=0;i<count;++i)  MessageBox(NULL,pszPorts[i],NULL,MB_OK);  for(int i=0;i<count;++i)  {     if(pszPorts[i])    {     delete [] pszPorts[i];     pszPorts[i]=NULL;    }    }

第二种 使用GetDefaultCommConfig

void __fastcall GetPortList(TStrings *strPortlist){    String strPortname;    COMMCONFIG   cc={0};    DWORD dwCCSize=sizeof(cc);    for(int i=1;i<64;i++)       {         strPortname=String().sprintf("COM%d",i);         if(GetDefaultCommConfig(strPortname.c_str(),&cc,&dwCCSize))           {            strPortlist->Add(strPortname);         }         strPortname="";    } }