本文介绍了在 Windows 上列出串行 (COM) 端口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种可靠的方法来列出 Windows 机器上的可用串行 (COM) 端口.有 这篇关于使用 WMI 的帖子,但我想要一些不那么具体的 .NET- 我想在没有 .NET 的情况下获取 Python 或 C++ 程序中的端口列表.

I'm looking for a robust way to list the available serial (COM) ports on a Windows machine. There's this post about using WMI, but I would like something less .NET specific - I want to get the list of ports in a Python or a C++ program, without .NET.

我目前知道另外两种方法:

I currently know of two other approaches:

  1. 读取 HARDWARE\DEVICEMAP\SERIALCOMM 注册表项中的信息.这看起来是个不错的选择,但它是否强大?我无法在网上或 MSDN 中找到此注册表单元确实始终包含可用端口的完整列表的保证.

  1. Reading the information in the HARDWARE\DEVICEMAP\SERIALCOMM registry key. This looks like a great option, but is it robust? I can't find a guarantee online or in MSDN that this registry cell indeed always holds the full list of available ports.

尝试在 COMN 上调用 CreateFile,其中 N 是从 1 到某事的数字.这还不够好,因为某些 COM 端口未命名为 COMN.例如,创建的一些虚拟 COM 端口被命名为 CSNA0、CSNB0 等,所以我不会依赖这种方法.

Tryint to call CreateFile on COMN with N a number from 1 to something. This isn't good enough, because some COM ports aren't named COMN. For example, some virtual COM ports created are named CSNA0, CSNB0, and so on, so I wouldn't rely on this method.

还有其他方法/想法/经验可以分享吗?

Any other methods/ideas/experience to share?

顺便说一下,这是一个从注册表读取端口名称的简单 Python 实现:

by the way, here's a simple Python implementation of reading the port names from registry:

import _winreg as winreg
import itertools


def enumerate_serial_ports():
    """ Uses the Win32 registry to return a iterator of serial
        (COM) ports existing on this computer.


    """
    path = 'HARDWARE\DEVICEMAP\SERIALCOMM'
    try:
        key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, path)
    except WindowsError:
        raise IterationError

    for i in itertools.count():
        try:
            val = winreg.EnumValue(key, i)
            yield (str(val[1]), str(val[0]))
        except EnvironmentError:
            break

推荐答案

有多种选择:

  1. 调用 QueryDosDeviceNULL lpDeviceName 列出所有 DOS 设备.然后使用 CreateFile 和 GetCommConfig 与每个设备名称转过来看看是不是串口.

  1. Call QueryDosDevice with a NULL lpDeviceName to list all DOS devices. Then use CreateFile and GetCommConfig with each device name in turn to figure out whether it's a serial port.

使用 GUID_DEVINTERFACE_COMPORT 的 ClassGuid 调用 SetupDiGetClassDevs.

Call SetupDiGetClassDevs with a ClassGuid of GUID_DEVINTERFACE_COMPORT.

WMI 也可用于 C/C++程序.

win32 新闻组 和一个 CodeProject,呃,项目.

There's some conversation on the win32 newsgroup and a CodeProject, er, project.

这篇关于在 Windows 上列出串行 (COM) 端口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 07:45