如何查找可用的COM端口?

16

如何找到电脑中可用的COM端口?我正在使用1.1框架。是否可能找到所有COM端口?如果可能,请帮助我解决问题。

9个回答

33

可能是你没有正确安装驱动程序。它是否在超级终端中显示? - Vanuan
驱动程序已安装,其他软件可以连接它们,包括超级终端。这些是基于FTDI USB<->串行的设备。我最终使用了来自此答案的QueryDosDevices:https://dev59.com/questions/LXM_5IYBdhLWcg3waSb9 - Jon Cage

14

正如其他人建议的那样,您可以使用WMI。 您可以在CodeProject中找到一个示例

try
{
    ManagementObjectSearcher searcher =
        new ManagementObjectSearcher("root\\WMI",
        "SELECT * FROM MSSerial_PortName");

    foreach (ManagementObject queryObj in searcher.Get())
    {
        Console.WriteLine("-----------------------------------");
        Console.WriteLine("MSSerial_PortName instance");
        Console.WriteLine("-----------------------------------");
        Console.WriteLine("InstanceName: {0}", queryObj["InstanceName"]);

        Console.WriteLine("-----------------------------------");
        Console.WriteLine("MSSerial_PortName instance");
        Console.WriteLine("-----------------------------------");
        Console.WriteLine("PortName: {0}", queryObj["PortName"]);

        //If the serial port's instance name contains USB 
        //it must be a USB to serial device
        if (queryObj["InstanceName"].ToString().Contains("USB"))
        {
            Console.WriteLine(queryObj["PortName"] + " 
            is a USB to SERIAL adapter/converter");
        }
    }
}
catch (ManagementException e)
{
    Console.WriteLine("An error occurred while querying for WMI data: " + e.Message);
} 

5
这段代码在 .NET Framework 4.0 上的“foreach”行会产生错误。 - Nick Binnet
有没有 Python 的等效代码? - Annapoornima Koppad
对于Python,你应该使用pyserial——它内置了查询com口的功能(请参见http://pyserial.readthedocs.io/en/latest/tools.html-列表端口)。 - drojf

9

可用的串口还可以在注册表中的键 HKEY_LOCAL_MACHINE\hardware\devicemap\serialcomm 的值中找到。


4
询问操作系统的问题,直接明了一些如何?
using System;
using System.Collections.Generic;
using Microsoft.Win32;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;

public class MyClass
{
    private const uint GENERIC_ALL = 0x10000000;
    private const uint GENERIC_READ = 0x80000000;
    private const uint GENERIC_WRITE = 0x40000000;
    private const uint GENERIC_EXECUTE = 0x20000000;    
    private const int OPEN_EXISTING = 3;    
    public const int INVALID_HANDLE_VALUE = -1;

    public static void Main()
    {
        for (int i = 1; i <= 32; i++)
            Console.WriteLine ("Port {0}: {1}", i, PortExists (i));
    }

    private static bool PortExists (int number) {
        SafeFileHandle h = CreateFile (@"\\.\COM" + number.ToString (), GENERIC_READ + GENERIC_WRITE, 
            0, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero);

        bool portExists = !h.IsInvalid;

        if (portExists)
            h.Close ();

        return portExists;
    }

    [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
    private static extern SafeFileHandle CreateFile (string lpFileName, System.UInt32 dwDesiredAccess, 
        System.UInt32 dwShareMode, IntPtr pSecurityAttributes, System.UInt32 dwCreationDisposition, 
        System.UInt32 dwFlagsAndAttributes, IntPtr hTemplateFile);
}

3
好的,有个要注意的地方!这将告诉你应用程序使用的端口是否可用。如果另一个应用程序占用了该端口,则PortExists函数将返回false。如果您想获取硬件可用端口的列表(即使被其他应用程序占用),则需要调用PInvoke GetDefaultCommConfig函数(http://msdn.microsoft.com/en-us/library/aa363262(VS.85).aspx)。 - Hemant

1

WMI 包含大量硬件信息。查询 Win32_SerialPort 实例。

(另一方面,我不记得 .NET 1.1 中有多少 WMI 查询支持。)


1

在 .net v1.1 中没有 SerialPort 通信的支持。最常见的解决方案是使用来自 VB6.0 安装的 MSCOMMCTL Active X 控件(从“添加引用”对话框中将其作为 COM 组件导入到您的 .net 项目中)。

在后续版本中,串口支持通过 System.IO.Ports 命名空间提供。另外请注意,没有 API 可以让您获得可用端口列表。

您可以获取所有端口名称的列表,然后尝试打开连接。如果端口已经在使用中,则会引发异常。


1

使用 QueryDosDevice API 函数。以下是 VB6 代码片段:

    ReDim vRet(0 To 255)

    sBuffer = String(100000, 1)
    Call QueryDosDevice(0, sBuffer, Len(sBuffer))
    sBuffer = Chr$(0) & sBuffer
    For lIdx = 1 To 255
        If InStr(1, sBuffer, Chr$(0) & "COM" & lIdx & Chr$(0), vbTextCompare) > 0 Then
            vRet(lCount) = "COM" & lIdx
            lCount = lCount + 1
        End If
    Next

1

由于您正在使用 .net 1.1,一个选项是使用 AxMSCommLib 控件。

这里有一个网页帮助我开始使用 AxMSCommLib 控件。甚至列出了一个可以轻松修改的 FindDevicePort() 方法。

我后来转而使用 System.IO.Ports,它似乎更加强大。

http://www.devhood.com/tutorials/tutorial_details.aspx?tutorial_id=320

谢谢


1
也许这对你有用?
我将向您展示一种简单的方法来检查PC中的所有COM端口。要开始,请按照以下步骤操作:
  1. Create a WinForms application in Visual Studio.
  2. Darg and drop a comboBox in your form and name it comboBoxCOMPORT
  3. Copy the following code and paste after the public Form1() method (autogenerated).

    private void Form1_Load(object sender, EventArgs e)
    {
        string[] ports = SerialPort.GetPortNames();        
       comboBoxCOMPORT.Items.AddRange(ports);
    }
    
  4. Run the app and click on drop down arrow on the comboBox to reveal all the available COM PORTS.
上述方法适用于Edgeport USB转串口转换器以及虚拟端口。我在我的项目中实施了这一方法,并且运行顺畅。如果需要进一步的帮助,请告诉我。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接