首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何以编程方式在C# (serialPort类)中查找所有可用的波特率

如何以编程方式在C# (serialPort类)中查找所有可用的波特率
EN

Stack Overflow用户
提问于 2009-07-22 14:28:58
回答 3查看 23.6K关注 0票数 18

有没有办法通过C#找出特定系统支持的所有可用波特率?这可以通过设备管理器-->端口获得,但我想以编程的方式列出它们。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2009-07-23 14:26:21

我已经找到了几种方法来做到这一点。以下两个文档是一个起点

  • http://support.microsoft.com/default.aspx/kb/99026
  • http://msdn.microsoft.com/en-us/library/aa363189(VS.85).aspx

线索在第一个文档的下一段中。

确定特定串行端口上可用的波特率的最简单方法是调用GetCommProperties()应用程序编程接口(

)并检查COMMPROP.dwSettableBaud位掩码,以确定该串行端口支持的波特率。

在此阶段,在C#中有两种方法可供选择:

1.0按如下方式使用interop (P/Invoke):

定义以下数据结构

代码语言:javascript
复制
[StructLayout(LayoutKind.Sequential)]
struct COMMPROP
{
    short wPacketLength;
    short wPacketVersion;
    int dwServiceMask;
    int dwReserved1;
    int dwMaxTxQueue;
    int dwMaxRxQueue;
    int dwMaxBaud;
    int dwProvSubType;
    int dwProvCapabilities;
    int dwSettableParams;
    int dwSettableBaud;
    short wSettableData;
    short wSettableStopParity;
    int dwCurrentTxQueue;
    int dwCurrentRxQueue;
    int dwProvSpec1;
    int dwProvSpec2;
    string wcProvChar;
}

然后定义以下签名

代码语言:javascript
复制
[DllImport("kernel32.dll")]
static extern bool GetCommProperties(IntPtr hFile, ref COMMPROP lpCommProp);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern IntPtr CreateFile(string lpFileName, int dwDesiredAccess,
           int dwShareMode, IntPtr securityAttrs, int dwCreationDisposition, 
           int dwFlagsAndAttributes, IntPtr hTemplateFile);

现在进行以下调用(请参阅http://msdn.microsoft.com/en-us/library/aa363858(VS.85).aspx

代码语言:javascript
复制
   COMMPROP _commProp = new COMMPROP();
   IntPtr hFile = CreateFile(@"\\.\" + portName, 0, 0, IntPtr.Zero, 3, 0x80, IntPtr.Zero);
   GetCommProperties(hFile, ref commProp);

其中portName类似于COM??(COM1、COM2等)。commProp.dwSettableBaud现在应该包含所需的信息。

2.0使用C#反射

可以使用反射来访问SerialPort BaseStream,然后访问所需的数据,如下所示:

代码语言:javascript
复制
   _port = new SerialPort(portName);
   _port.Open();
   object p = _port.BaseStream.GetType().GetField("commProp", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(_port.BaseStream);
   Int32 bv = (Int32)p.GetType().GetField("dwSettableBaud", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public).GetValue(p);

请注意,在上述两种方法中,必须至少打开端口一次才能获取此数据。

票数 15
EN

Stack Overflow用户

发布于 2009-07-22 14:51:30

我觉得你做不到。

我最近遇到了这个问题,最终硬编码了我想要使用的波特率。

MSDN简单地说,“波特率必须由用户的串行驱动程序支持”。

票数 0
EN

Stack Overflow用户

发布于 2017-02-10 07:43:41

代码语言:javascript
复制
dwSettableBaud  gives 268894207 int (0x1006ffff)
while dwMaxBaud gives 268435456 int (0x10000000)

显然,这对我没有帮助。这就是我目前所依赖的:

代码语言:javascript
复制
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;


  public static readonly List<string> SupportedBaudRates = new List<string>
{
    "300",
    "600",
    "1200",
    "2400",
    "4800",
    "9600",
    "19200",
    "38400",
    "57600",
    "115200",
    "230400",
    "460800",
    "921600"
};

    public static int MaxBaudRate(string portName)
    {
        var maxBaudRate = 0;
        try
        {
            //SupportedBaudRates has the commonly used baudRate rates in it
            //flavor to taste
            foreach (var baudRate in ConstantsType.SupportedBaudRates)
            {
                var intBaud = Convert.ToInt32(baudRate);
                using (var port = new SerialPort(portName))
                {
                    port.BaudRate = intBaud;
                    port.Open();
                }
                maxBaudRate = intBaud;
            }
        }
        catch
        {
            //ignored - traps exception generated by
            //baudRate rate not supported
        }

        return maxBaudRate;
    }

波特率是以字符串形式出现的,因为它们的目的地是组合框。

代码语言:javascript
复制
    private void CommPorts_SelectedIndexChanged(object sender, EventArgs e)
    {
        var combo = sender as ComboBox;
        if (combo != null)
        {
            var port = combo.Items[combo.SelectedIndex].ToString();
            var maxBaud = AsyncSerialPortType.MaxBaudRate(port);
            var baudRates = ConstantsType.SupportedBaudRates;
            var f = (SerialPortOpenFormType)(combo.Parent);
            f.Baud.Items.Clear();
            f.Baud.Items.AddRange(baudRates.Where(baud => Convert.ToInt32(baud) <= maxBaud).ToArray());
        }
    }

如果您知道计划打开的所有串行端口支持的最低波特率,则可以提高性能。例如,从115,200开始似乎是本世纪生产的串行端口的安全下限。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1165692

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档