导航

获取系统可用串口个数及串口名称

Posted on 2009-08-10 13:35  ccjvl  阅读(1856)  评论(0编辑  收藏  举报

在c#中可以很方便的实现:

 

Code

 

 

下面为转载的其他网站的方法,代码使用C++编写:

第一个思路应该是用建立串口的方式来取得串口名,若建立失败,则此串口不存在
void GetComList() {
  CString strCom;
  int nCom = 0;
  int count = 0;
  HANDLE hCom;
  do {
    nCom++;
    strCom.Format("COM%d", nCom);
    hCom = CreateFile(strCom, 0, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
    if (INVALID_HANDLE_VALUE == hCom)
      break;
    m_cbComList.AddString(strCom);
    CloseHandle(hCom);
  } while (1);
}

//-------------------------------------------------------------- -

第二个思路是获取注册表中记录的信息

// 串口信息都是保存在注册表的这个位置的 // HKEY_LOCAL_MACHINEHARDWAREDEVICEMAPSERIALCOMM
HKEY hKey;
LONG ret;
OSVERSIONINFO osvi;
BOOL bOsVersionInfoEx;
char keyinfo[100],
     comm_name[40],
     ValueName[40];
int i;
DWORD sType,
      Reserved,
      cbData,
      cbValueName;
hIcon = AfxGetApp() - > LoadIcon(IDI_HARDWARE);
SetIcon(hIcon, false);
ZeroMemory( & osvi, sizeof(OSVERSIONINFO));
osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
memset(keyinfo, 0, 100);
strcpy(keyinfo, "HARDWARE\DEVICEMAP\SERIALCOMM");
i = 0;
sType = REG_SZ;
Reserved = 0;
bOsVersionInfoEx = GetVersionEx( & osvi);
ret = RegOpenKeyEx(HKEY_LOCAL_MACHINE, keyinfo, 0, KEY_ALL_ACCESS, & hKey);
if (ret == ERROR_SUCCESS) {
  if (osvi.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) {
    for (i = 1; i <= 128; i++) {
      sprintf(comm_name, "COM%d", i);
      if (CommPortIsUsed(comm_name) == 1)
        m_comlist.AddString(comm_name);
    }
  } else if (osvi.dwPlatformId == VER_PLATFORM_WIN32_NT) {
    do {
      cbData = 40;
      cbValueName = 40;
      memset(comm_name, 0, 40);
      memset(ValueName, 0, 40);
      ret = RegEnumValue(hKey, i, ValueName, & cbValueName, NULL, & sType, (LPBYTE) comm_name, & cbData);
      if (ret == ERROR_SUCCESS) {
        if (CommPortIsUsed(comm_name) == 1) m_comlist.AddString(comm_name);
        i++;
      }
    } while (ret == ERROR_SUCCESS);
  }
}


本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/particle_1979/archive/2006/12/31/1471003.aspx