简体   繁体   English

如何自动检测并连接到USB设备?

[英]How to automatically detect and connect to usb device?

I have an usb device (RF badge reader), and I need my application to detect for witch COM Port the device is plugged. 我有一个USB设备(RF徽章读取器),并且我需要我的应用程序来检测是否已插入设备的COM端口。 what I`m doing now is like this: 我现在正在做的是这样的:

    SerialPort mySerialPort = new SerialPort("COM3");
    mySerialPort.BaudRate = 9600;
    mySerialPort.Parity = Parity.None;
    mySerialPort.StopBits = StopBits.One;
    mySerialPort.DataBits = 8;
    mySerialPort.Handshake = Handshake.None;
    mySerialPort.Open();

If I connect the device to another USB port, the application crashes. 如果我将设备连接到另一个USB端口,则应用程序崩溃。 Any Idea how to do this ? 任何想法如何做到这一点?

For most USB-Serial devices the COM port will change if you connect to another USB port. 对于大多数USB串行设备,如果您连接到另一个USB端口,则COM端口将更改。 That's why it crashs when you try to open COM3. 这就是为什么当您尝试打开COM3时它崩溃的原因。

Your best option is probably to make the COM port (COM3) a user configurable setting. 最好的选择可能是使COM端口(COM3)成为用户可配置的设置。 You shouldn't disconnect/reconnect the USB device while it is used, so you actually don't need an auto detection. 使用USB设备时,请勿断开/重新连接它,因此实际上不需要自动检测。

You may, however, try to detect USB changes (find it on SO, for instance) and auto sense your device (involves a bit of communication). 但是,您可以尝试检测USB的变化(例如,在SO上找到它)并自动检测您的设备(涉及一些通信)。 If you succeed or not may depend on the USB device driver. 如果成功与否,可能取决于USB设备驱动程序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM