gpt4 book ai didi

c# - 新的 COM 端口可用事件

转载 作者:太空狗 更新时间:2023-10-29 21:18:41 25 4
gpt4 key购买 nike

我的 C# 应用程序使用 COM 端口。我遇到了一些大多数程序都应该遇到的困难。当端口名称列表更改时,我需要得到一个事件。我有一个选择框,用户可以从可用端口名称列表中进行选择。有人有这方面的代码片段吗?谢谢。

最佳答案

也可以在“ManagementEventWatcher”的帮助下完成:

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel.Composition;
using System.Linq;
using System.Text;
using System.Management;
using System.IO.Ports;
using System.Threading;
using System.Threading.Tasks;

namespace HmxFlashLoader
{
/// <summary>
/// Make sure you create this watcher in the UI thread if you are using the com port list in the UI
/// </summary>
[Export]
[PartCreationPolicy(CreationPolicy.Shared)]
public sealed class SerialPortWatcher : IDisposable
{
public SerialPortWatcher()
{
_taskScheduler = TaskScheduler.FromCurrentSynchronizationContext();
ComPorts = new ObservableCollection<string>(SerialPort.GetPortNames().OrderBy(s => s));

WqlEventQuery query = new WqlEventQuery("SELECT * FROM Win32_DeviceChangeEvent");

_watcher = new ManagementEventWatcher(query);
_watcher.EventArrived += (sender, eventArgs) => CheckForNewPorts(eventArgs);
_watcher.Start();
}

private void CheckForNewPorts(EventArrivedEventArgs args)
{
// do it async so it is performed in the UI thread if this class has been created in the UI thread
Task.Factory.StartNew(CheckForNewPortsAsync, CancellationToken.None, TaskCreationOptions.None, _taskScheduler);
}

private void CheckForNewPortsAsync()
{
IEnumerable<string> ports = SerialPort.GetPortNames().OrderBy(s => s);

foreach (string comPort in ComPorts)
{
if (!ports.Contains(comPort))
{
ComPorts.Remove(comPort);
}
}

foreach (var port in ports)
{
if (!ComPorts.Contains(port))
{
AddPort(port);
}
}
}

private void AddPort(string port)
{
for (int j = 0; j < ComPorts.Count; j++)
{
if (port.CompareTo(ComPorts[j]) < 0)
{
ComPorts.Insert(j, port);
break;
}
}

}

public ObservableCollection<string> ComPorts { get; private set; }

#region IDisposable Members

public void Dispose()
{
_watcher.Stop();
}

#endregion

private ManagementEventWatcher _watcher;
private TaskScheduler _taskScheduler;
}
}

关于c# - 新的 COM 端口可用事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10550635/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com