• C++多种方法枚举串口号


    部分方式没结果,思路应该是没错。

      //7.
      std::cout << "M8: SetupDiGetClassDevs " << std::endl;
      //HDEVINFO hDevInfoSet = SetupDiGetClassDevs(&GUID_DEVINTERFACE_COMPORT, nullptr, nullptr, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
      HDEVINFO hDevInfoSet = SetupDiGetClassDevs(&GUID_DEVINTERFACE_SERENUM_BUS_ENUMERATOR, nullptr, nullptr, DIGCF_PRESENT);
      if (hDevInfoSet != INVALID_HANDLE_VALUE)
      {
        int nIndex = 0;
        while (true)
        {
          SP_DEVINFO_DATA spDevInfo;
          spDevInfo.cbSize = sizeof(SP_DEVINFO_DATA);
          if (SetupDiEnumDeviceInfo(hDevInfoSet, nIndex++, &spDevInfo))
          {
            ATL::CRegKey RegKey;
            RegKey.Attach(SetupDiOpenDevRegKey(hDevInfoSet, &spDevInfo, DICS_FLAG_GLOBAL, 0, DIREG_DEV, KEY_QUERY_VALUE));
    
            unsigned char szSerialPort[256] = { 0 };
            unsigned long szSerialPortSize = sizeof(szSerialPort);
            if (ERROR_SUCCESS == RegKey.QueryStringValue("PortName", (char*)szSerialPort, &szSerialPortSize))
            {
              std::cout << szSerialPort << std::endl;
            }
            RegKey.Detach();
            RegKey.Close();
            continue;
          }
          break;
        }
        SetupDiDestroyDeviceInfoList(hDevInfoSet);
      }
    
    
      //6.  //test: win7 no results
      std::cout << "M6: WMI " << std::endl;
      //HRESULT hResult = CoInitialize(nullptr);
      HRESULT hResult = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
      if (!FAILED(hResult))
      {
        hResult = CoInitializeSecurity(nullptr, -1, nullptr, nullptr, RPC_C_AUTHN_LEVEL_DEFAULT, RPC_C_IMP_LEVEL_IMPERSONATE, nullptr, EOAC_NONE, nullptr);
    
        if (!FAILED(hResult))
        {
          IWbemLocator* pLocator = NULL;
          //ATL::CComPtr<IWbemLocator> pLocator;
          hResult = CoCreateInstance(CLSID_WbemLocator, nullptr, CLSCTX_INPROC_SERVER, IID_IWbemLocator, reinterpret_cast<void**>(&pLocator));
          if (!FAILED(hResult))
          {
            IWbemServices* pServices = NULL;
            //ATL::CComPtr<IWbemServices> pServices;
            hResult = pLocator->ConnectServer(L"ROOT\CimV2", nullptr, nullptr, nullptr, 0, nullptr, nullptr, &pServices);
            if (!FAILED(hResult))
            {
              IEnumWbemClassObject* pClassObject = NULL;
              //ATL::CComPtr<IEnumWbemClassObject> pClassObject;
              hResult = pServices->CreateInstanceEnum(L"Win32_SerialPort", WBEM_FLAG_RETURN_IMMEDIATELY | WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_WBEM_COMPLETE, nullptr, &pClassObject);
              if (!FAILED(hResult))
              {
                hResult = WBEM_S_NO_ERROR;
                while (WBEM_S_NO_ERROR == hResult)
                {
                  unsigned long nReturned;
                  IWbemClassObject* pArrClassObject;
                  //ATL::CComPtr<IWbemClassObject> pArrClassObject[10];
                  //hResult = pClassObject->Next(WBEM_INFINITE, 10, reinterpret_cast<IWbemClassObject**>(pArrClassObject), &nReturned);
                  hResult = pClassObject->Next(WBEM_INFINITE, 1, &(pArrClassObject), &nReturned);
                  //hResult = 0x80041003
                  if (SUCCEEDED(hResult))
                  {
                    for (unsigned long i = 0; i < nReturned; i++)
                    {
                      VARIANT stVariant;
                      HRESULT hGet = pArrClassObject->Get(L"DeviceID", 0, &stVariant, nullptr, nullptr);
                      if (SUCCEEDED(hGet) && stVariant.vt == VT_BSTR)
                      {
                        /*std::string item = stVariant.bstrVal;
                        if (0 == item.compare(0, 3, "COM"))*/
                        std::cout << stVariant.bstrVal << std::endl;
                      }
                      VariantClear(&stVariant);
                      pArrClassObject->Release();
                    }
                  }
                }
                pClassObject->Release();
              }
              pServices->Release();
            }
            pLocator->Release();
          }
        }
        CoUninitialize();
      }
    
    
      //5.  //test: win7 no results
      std::cout << "M5: ComDBGetCurrentPortUsage " << std::endl;
      HCOMDB hComDB = nullptr;
      if (ERROR_SUCCESS == ComDBOpen(&hComDB))
      {
        unsigned long nComDBBufferSize = 0;
        if (ERROR_SUCCESS == ComDBGetCurrentPortUsage(hComDB, nullptr, 0, CDB_REPORT_BYTES, &nComDBBufferSize))
        {
          unsigned char* szComDBBuffer = new unsigned char[nComDBBufferSize]();
          if (ERROR_SUCCESS == ComDBGetCurrentPortUsage(hComDB, szComDBBuffer, nComDBBufferSize, CDB_REPORT_BYTES, &nComDBBufferSize))
          {
            for (size_t i = 0; i < nComDBBufferSize; i++)
            {
             /* std::string item = szComDBBuffer;
              if (0 == item.compare(0, 3, "COM"))*/
              std::cout << szComDBBuffer << std::endl;
            }
          }
          delete[] szComDBBuffer;
        }
        ComDBClose(hComDB);
      }
    
      //4.  //test: win7 no results
      std::cout << "M4: EnumPorts " << std::endl;
      unsigned long nNeeded = 0, nPortsSize = 0;
      if (!EnumPorts(nullptr, 2, nullptr, 0, &nNeeded, &nPortsSize))
      {
        unsigned long nError = GetLastError();
        if (RPC_S_SERVER_UNAVAILABLE == nError)
          std::cout << "SERVER_UNAVAILABLE" << std::endl;
        else
          std::cout << "Unknown Error " << nError << std::endl;    
      }
      else
      {
        unsigned char* szEnumPortsBuffer = new unsigned char[nNeeded]();
        if (EnumPorts(nullptr, 2, szEnumPortsBuffer, nNeeded, &nNeeded, &nPortsSize))
        {
          PORT_INFO_2* pPortInfo2 = reinterpret_cast<PORT_INFO_2*>(szEnumPortsBuffer);
          for (size_t i = 0; i < nPortsSize; i++)
          {
            std::string item = pPortInfo2->pPortName;
            if (0 == item.compare(0, 3, "COM"))
              std::cout << item << std::endl;
          }
        }
        delete[] szEnumPortsBuffer;
      }
    
    
      //3. 
      std::cout << "M3: QueryDosDevice " << std::endl;
      unsigned long nResultLength = 0;
      unsigned long nBufferLengthTemp = 1024;
      char* szpBuffer = new char[nBufferLengthTemp]();
      do
      {
        nResultLength = QueryDosDevice(nullptr, szpBuffer, nBufferLengthTemp);
        if (0 == nResultLength && ERROR_INSUFFICIENT_BUFFER == GetLastError())
        {
          delete[] szpBuffer;
          nBufferLengthTemp *= 2;
          szpBuffer = new char[nBufferLengthTemp]();
          continue;
        }
        break;
      } while (true);
      char* szpBufferMovable = szpBuffer;
      do
      {
        std::string item = szpBufferMovable;
        if (0 == item.compare(0, 3, "COM"))
          std::cout << item << std::endl;
    
        nResultLength -= (item.length() + 1);
        szpBufferMovable += (item.length() + 1);
      } while (0 < nResultLength);
      delete[] szpBuffer;
    
    
      //2. 
      std::cout << "M2: RegQueryValue " << std::endl;
      ATL::CRegKey RegKey;
      if (ERROR_SUCCESS == RegKey.Open(HKEY_LOCAL_MACHINE, "HARDWARE\DEVICEMAP\SERIALCOMM", KEY_QUERY_VALUE))
      {
        unsigned long nIndex = 0;
        while (true)
        {
          char szPorts[2048] = { 0 };
          unsigned long nPorts = sizeof(szPorts);
          //一般为 ERROR_ACCESS_DENIED == 5
          //if (ERROR_SUCCESS == RegKey.EnumKey(nIndex++, szPorts, &nPorts))
          if (ERROR_SUCCESS == RegEnumValue(RegKey, nIndex++, szPorts, &nPorts, nullptr, nullptr, nullptr, nullptr))
          {
            char szPortsValue[1024] = { 0 };
            unsigned long nPortsValue = sizeof(szPortsValue);
            if (ERROR_SUCCESS == RegKey.QueryStringValue(szPorts, szPortsValue, &nPortsValue))
            {
              std::cout << szPortsValue << std::endl;
              continue;
            }
          }
          break;
        }
        RegKey.Close();
      }
    
      //1. 
      std::cout << "M1: CreateFile " << std::endl;
      for (size_t i = 0; i < 256; i++)
      {
        char szPorts[16] = { 0 };
        sprintf(szPorts, "\\.\COM%d", i);
        HANDLE hPorts = CreateFile(szPorts, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);
        if (INVALID_HANDLE_VALUE != hPorts)
        { 
          std::cout << szPorts << std::endl;
          CloseHandle(hPorts);
        }
      }

     相关头文件库

    using namespace std;
    #include <string> 
    #include <vector>
    #include <iostream> 
    #include <Windows.h>
    #include <atlbase.h>    //ATL::CRegKey
    #include <winspool.h>  //EnumPorts
    #include <msports.h>  //ComDBOpen
    #pragma comment(lib, "msports.lib")
    #include <WbemCli.h> //CLSID_WbemLocator 
    #pragma comment(lib, "WbemUuid.lib")
    #include <setupapi.h> //SetupDiGetClassDevs
  • 相关阅读:
    05流程图和流程定义的操作
    04启动流程实例,任务的查询与完成
    03流程图的绘制与部署
    02数据库表的初始化方式
    01环境安装
    JavaScript基础和JavaScript内置对象:
    用手机、pid作为win电脑扩展屏
    H5新增特性之语义化标签
    盒模型
    CSS定位总结--static、relative、absolute、fixed
  • 原文地址:https://www.cnblogs.com/wjshan0808/p/8934743.html
Copyright © 2020-2023  润新知