Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How might I receive notifications when a USB device is connected?

Tags:

c#

device

usb

I'm writing a program to monitor a specific device. This device may or may not always be connected, and when connected may be connected to any one of several different ports; I'd like my program to handle this gracefully.

Is there a way to receive notifications when a specific USB device is connected, and from there to determine which port it is connected to?

like image 368
RV. Avatar asked Nov 14 '22 16:11

RV.


1 Answers

To get an information if any hardware device has changed you can add the following code to your main form:

/// <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);
}
like image 90
Oliver Avatar answered Dec 18 '22 21:12

Oliver