You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在UWP应用中访问原生硬件RS-232端口(非USB转RS-232适配器)

能否在UWP应用中访问原生硬件RS-232端口?

答案是:目前UWP并不支持直接访问原生硬件RS-232端口(即非USB转RS-232的内置串口),具体细节如下:

  • 关于Windows.Devices.SerialCommunication命名空间的支持范围:

    官方文档明确说明,当前版本的该命名空间仅支持属于USB CDC设备类的设备,包括串口转USB适配器、Arduino Uno R3这类带有内置USB转串口桥接芯片的设备所暴露的端口。

  • 枚举与打开的差异:
    你可以通过DeviceInformation.FindAllAsync()方法枚举到系统内置或机箱上的原生串口设备,但当你尝试调用SerialDevice.FromIdAsync()打开这类设备时,会直接失败——因为原生串口并未被纳入该命名空间的支持范畴。

  • 替代方案(如果需要访问原生串口):
    如果你的场景必须在UWP环境下访问原生RS-232端口,可以考虑使用**桌面桥接(Desktop Bridge)**技术:将传统的桌面应用(比如用.NET Framework编写的、能直接访问原生串口的应用)打包成UWP格式,借助桌面应用的API来实现对原生串口的访问,不过这需要额外的权限配置和打包操作。

代码示例:枚举串口并尝试打开

using Windows.Devices.Enumeration;
using Windows.Devices.SerialCommunication;
using System.Diagnostics;

// 枚举所有可检测到的串口设备
var deviceSelector = SerialDevice.GetDeviceSelector();
var devices = await DeviceInformation.FindAllAsync(deviceSelector);

foreach (var device in devices)
{
    Debug.WriteLine($"设备ID: {device.Id}, 设备名称: {device.Name}");
    
    // 尝试打开设备(原生串口会失败)
    try
    {
        SerialDevice serialDevice = await SerialDevice.FromIdAsync(device.Id);
        if (serialDevice == null)
        {
            Debug.WriteLine($"⚠️ 无法打开设备: {device.Name}(大概率是原生RS-232端口)");
        }
        else
        {
            Debug.WriteLine($"✅ 成功打开设备: {device.Name}");
            // 后续操作...
            serialDevice.Dispose();
        }
    }
    catch (Exception ex)
    {
        Debug.WriteLine($"❌ 打开设备出错: {ex.Message}");
    }
}

内容的提问来源于stack exchange,提问作者Dan Is Fiddling By Firelight

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 08:12:55