枚举串口

来源:互联网 发布:js 取消input选中 编辑:程序博客网 时间:2024/05/01 05:27

 void  GetAllComPorts(CString *pPortList)
{
 //int k=0;
 long   lReg;
 HKEY   hKey;
 DWORD   MaxValueLength;
 DWORD   dwValueNumber;

 lReg=RegOpenKeyExA(HKEY_LOCAL_MACHINE,
  "HARDWARE//DEVICEMAP//SERIALCOMM",
  0,
  KEY_QUERY_VALUE,
  &hKey);

 if(lReg!=ERROR_SUCCESS) //成功时返回ERROR_SUCCESS,
 {
  AfxMessageBox(L"Open   Registry   Error!/n");
  
  exit(0);
 }
 
 lReg=RegQueryInfoKeyA(hKey,
   NULL,
   NULL,
   NULL,
   NULL,
   NULL,
   NULL,
   &dwValueNumber, //返回和hKey关联的值
   &MaxValueLength,
   NULL,
   NULL,
   NULL);
 if(lReg!=ERROR_SUCCESS) //没有成功
 {
  AfxMessageBox(L"Getting   Info   Error!/n");
  
  exit(0);
 }
 
 LPSTR   pValueName,pCOMNumber;
 DWORD   cchValueName,dwValueSize=6;

 //printf("Number   of   SubKeys:%d/n",dwValueNumber);

 for(int   i=0;i < dwValueNumber;i++)
 {
  cchValueName=MaxValueLength+1;
  dwValueSize=6;
  pValueName=(LPSTR)VirtualAlloc(NULL,cchValueName,MEM_COMMIT,PAGE_READWRITE);
  lReg=RegEnumValueA(hKey,
  i,
  pValueName,
  &cchValueName,
  NULL,
  NULL,
  NULL,
  NULL);

  if((lReg!=ERROR_SUCCESS)&&(lReg!=ERROR_NO_MORE_ITEMS))
  {
   AfxMessageBox(L"Enum   Registry   Error or No More Items!/n");
   //printf("lreg:=%d/n",lReg);
   CString slReg;
   slReg.Format(L"%d",lReg);
   AfxMessageBox(slReg);
   exit(0);
  }

  pCOMNumber=(LPSTR)VirtualAlloc(NULL,6,MEM_COMMIT,PAGE_READWRITE);
  lReg=RegQueryValueExA(hKey,
  pValueName,
  NULL,
  NULL,
  (LPBYTE)pCOMNumber,
  &dwValueSize);
 
  if(lReg!=ERROR_SUCCESS)
  {
   AfxMessageBox(L"Can not get the name of the port");
   exit(0);
  }
 
  CString str2(pCOMNumber);//,str3;//str1(pPortList),
  *pPortList += L"," + str2;
  //strcat(pPortList,pCOMNumber);

  //k+=strlen(pCOMNumber);
  //k++;

  VirtualFree(pValueName,0,MEM_RELEASE);
  VirtualFree(pCOMNumber,0,MEM_RELEASE);
 }

}