SerialPort.GetPortNames() 行为

编程入门 行业动态 更新时间:2024-10-28 01:24:59
本文介绍了SerialPort.GetPortNames() 行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在我的 C# 2008 应用程序中,我使用 SerialPort.GetPortNames() 函数来检索当前可用端口的列表.我注意到的是,当我插入 USB 设备时,它的端口号会显示在我的应用程序的列表中,当我拔下它并刷新列表时,端口号不再存在.

In my C# 2008 application, I use the SerialPort.GetPortNames() function to retrieve the list of currently available ports. What I have noticed is, when ever I plug in a USB device, it's port number i s shown in the list on my Application and when I unplug it and refresh the list, the port number is no longer there.

应用程序的一个阶段涉及从/向设备连续读取/写入数据.现在,我的期望是,如果我在操作期间拔下设备并使用 SerialPort.GetPortNames() 获取当前端口列表,则端口名称将不存在,我可以使用它来决定设备已被拔掉.

One phase of the application involves reading/writing data from/to the device continuously. Now, my expectation is, If I unplug the device during the operation and get the current Port list using SerialPort.GetPortNames(), the Port Name will not be there and I can use that to make the decision that the device has been unplugged.

令我惊讶的是,尽管删除了端口名称,但仍然可以找到它

为什么程序会这样?在无通信模式下不会列出端口名称.是否与通信时被移除的设备有关?

Why is the program behaving like this? The port name isn't listed when in no-communication mode. Does it have something to do with the device being removed when it's communicating?

推荐答案

我假设您的意思是 System.IO.Ports.SerialPort.GetPortNames(),因为我在任何地方都找不到 GetPortList() 函数.MSDN 说:如果注册表包含陈旧或其他不正确的数据,则 GetPortNames 方法将返回不正确的数据",所以这可能是问题所在.我猜如果端口仍在使用",Windows 不会更新注册表,就像当程序有句柄时您无法删除文件一样.

I'm assuming you mean System.IO.Ports.SerialPort.GetPortNames(), because i could not find a GetPortList() function anywhere. MSDN says: "If the registry contains stale or otherwise incorrect data then the GetPortNames method will return incorrect data", so that's probably where the problem lies. I guess Windows doesn't update the registry if the port is still being 'used', just like you can't delete a file when a program has a handle on it.

如果您想测试设备是否被移除,您可以使用 Window API 调用来实现 (www.pinvoke/default.aspx/user32/RegisterDeviceNotification.html).希望有帮助!

If you want to test if the device is removed, you can do so with a Window API call (www.pinvoke/default.aspx/user32/RegisterDeviceNotification.html). Hope that helps!

更多推荐

SerialPort.GetPortNames() 行为

本文发布于:2023-11-11 04:49:01,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1577423.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:SerialPort   GetPortNames

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!