连接USB设备时如何收到通知?

时间:2009-04-21 05:59:55

标签: c# usb device

我正在编写一个监控特定设备的程序。此设备可能可能不会始终连接,并且当连接时可能连接到几个不同端口中的任何一个;我希望我的程序可以优雅地处理它。

有没有办法在连接特定USB设备时接收通知,并从那里确定连接到哪个端口?

2 个答案:

答案 0 :(得分:1)

在SO上查看this thread。特别是使用SharpUSBLib的接受答案。

答案 1 :(得分:1)

要获取有关任何硬件设备更改的信息,您可以将以下代码添加到主表单中:

/// <summary>
/// Windows Messages
/// Defined in winuser.h from Windows SDK v6.1
/// Documentation pulled from MSDN.
/// For more look at: http://www.pinvoke.net/default.aspx/Enums/WindowsMessages.html
/// </summary>
public enum WM : uint
{
    /// <summary>
    /// Notifies an application of a change to the hardware configuration of a device or the computer.
    /// </summary>
    DEVICECHANGE = 0x0219,
}

protected override void WndProc(ref Message m)
{
    switch ((WM)m.Msg)
    {
        case WM.DEVICECHANGE:
            //ToDo: put your code here.
            break;
    }
    base.WndProc(ref m);
}