How do I get the friendly name of a COM port in Windows?

后端 未结 8 1039
再見小時候
再見小時候 2020-12-05 08:09

I have a GSM modem connected via USB. The modem creates 2 serial ports. The first is automatically attached to the modem, the second shows in Device Manager as \"HUAWEI Mo

相关标签:
8条回答
  • 2020-12-05 08:40

    Used the method posted by LiGenChen. The method ComPortSetupAPISetupDiClassGuids gave the best time and friendly name.

    0 讨论(0)
  • 2020-12-05 08:50

    The information posted by Will Dean was most helpful. This is the code that eventually worked for me. Everything in the PInvoke class was taken verbatim from http://www.pinvoke.net . I did have to change a data type here or there to make it work (like when using an enum instead of a uint) but it should be easy to figure out.

    internal static string GetComPortByDescription(string Description)
    {
        string Result = string.Empty;
        Guid guid = PInvoke.GUID_DEVCLASS_PORTS;
        uint nDevice = 0;
        uint nBytes = 300;
        byte[] retval = new byte[nBytes];
        uint RequiredSize = 0;
        uint PropertyRegDataType = 0;
    
        PInvoke.SP_DEVINFO_DATA devInfoData = new PInvoke.SP_DEVINFO_DATA();
        devInfoData.cbSize = Marshal.SizeOf(typeof(PInvoke.SP_DEVINFO_DATA));
    
        IntPtr hDeviceInfo = PInvoke.SetupDiGetClassDevs(
            ref guid, 
            null, 
            IntPtr.Zero, 
            PInvoke.DIGCF.DIGCF_PRESENT);
    
        while (PInvoke.SetupDiEnumDeviceInfo(hDeviceInfo, nDevice++, ref devInfoData))
        {
            if (PInvoke.SetupDiGetDeviceRegistryProperty(
                    hDeviceInfo, 
                    ref devInfoData, 
                    PInvoke.SPDRP.SPDRP_FRIENDLYNAME,
                    out PropertyRegDataType, 
                    retval, 
                    nBytes, 
                    out RequiredSize))
            {
                if (System.Text.Encoding.Unicode.GetString(retval).Substring(0, Description.Length).ToLower() ==
                    Description.ToLower())
                {
                    string tmpstring = System.Text.Encoding.Unicode.GetString(retval);
                    Result = tmpstring.Substring(tmpstring.IndexOf("COM"),tmpstring.IndexOf(')') - tmpstring.IndexOf("COM"));
                } // if retval == description
            } // if (PInvoke.SetupDiGetDeviceRegistryProperty( ... SPDRP_FRIENDLYNAME ...
        } // while (PInvoke.SetupDiEnumDeviceInfo(hDeviceInfo, nDevice++, ref devInfoData))
    
        PInvoke.SetupDiDestroyDeviceInfoList(hDeviceInfo);
        return Result;
    }
    

    I think the line Result = tmpstring.Substring(tmpstring.IndexOf("COM"),tmpstring.IndexOf(')') - tmpstring.IndexOf("COM")); is a little clumsy, suggestions on how to clean it up would be appreciated.

    Thanks for your help with this matter Will, without you, I'd still be searching google.

    0 讨论(0)
提交回复
热议问题