SerialPort.GetPortNames() 行为 [英] SerialPort.GetPortNames() behavior

查看:29
本文介绍了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 调用来实现 (http://www.pinvoke.net/default.aspx/user32/RegisterDeviceNotification.html).希望有帮助!

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

这篇关于SerialPort.GetPortNames() 行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆