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

VS2022/.NET7 WinForm中如何使用UWP的Windows命名空间?

解决WinForm(.NET7)中通过USB VID/PID自动连接串口的问题

正确引入WinRT API的步骤

  • 卸载错误安装的Windows包:打开NuGet包管理器,找到已安装的Windows包并卸载,或者在Package Manager Console执行Uninstall-Package Windows
  • 安装官方WinRT互操作包:搜索并安装Microsoft.Windows.SDK.Contracts,这个包专门用于非UWP项目(如WinForm、WPF)调用WinRT API。根据你的Windows版本选择对应版本(比如Windows 10 22H2选10.0.22621.x系列),也可以用命令安装:
    Install-Package Microsoft.Windows.SDK.Contracts -Version 10.0.22621.755
    
  • 安装完成后,即可在代码中引用Windows.Devices.Usb、Windows.Devices.SerialCommunication等UWP命名空间

核心实现代码

using Windows.Devices.Usb;
using Windows.Devices.SerialCommunication;
using System.Threading.Tasks;

// 替换为你的设备VID和PID
private const uint TargetVid = 0x1234;
private const uint TargetPid = 0x5678;

private async Task ConnectTargetSerialPort()
{
    // 生成设备选择器
    string deviceSelector = UsbDevice.GetDeviceSelector(TargetVid, TargetPid);
    // 查找匹配的USB设备
    var deviceInfos = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(deviceSelector);

    if (deviceInfos.Count > 0)
    {
        // 打开第一个匹配的串口设备
        SerialDevice serialDevice = await SerialDevice.FromIdAsync(deviceInfos[0].Id);
        
        if (serialDevice != null)
        {
            // 配置串口参数(按需修改)
            serialDevice.BaudRate = 9600;
            serialDevice.DataBits = 8;
            serialDevice.Parity = SerialParity.None;
            serialDevice.StopBits = SerialStopBitCount.One;

            // 后续可添加串口读写逻辑
            // ...

            // 不用时记得释放资源
            // serialDevice.Dispose();
        }
    }
}

关键注意事项

  • 确认项目目标平台为Windows:右键项目→属性→应用程序→目标操作系统,选择Windows(.NET7默认可能是Any CPU,需手动指定)
  • 无需修改TargetPlatformVersion为8.0,保持项目默认的对应Windows SDK版本即可
  • 若仍无法识别命名空间,检查Microsoft.Windows.SDK.Contracts包版本是否与系统匹配,或尝试更新到最新兼容版本
  • 运行程序时确保设备驱动安装正常,必要时以管理员身份运行VS或程序以获取设备访问权限

内容的提问来源于stack exchange,提问作者na_sacc

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 08:10:22