0

In my application I use USB device for some operation, sometimes happens that the USB disconnected and connected again, after that I can't use the device from my application and to keep using it I need to restart the app, How could I use it without restarting my application?

after some help, I handled the event when I plug / unplug the device by adding the code"

    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:
                MessageBox.Show(m.ToString(), "USB Detected",MessageBoxButtons.OK,MessageBoxIcon.Information);
                break;
        }
        base.WndProc(ref m);
    }

the output is:

{msg=0x219 (WM_DEVICECHANGE) hwnd=0x90242 wparam=0x7 lparam=0x0 result=0x0}

the problem is that I need more information that will indicate that it's the correct device

tried to use SharpUSBLib dll for that purpose without success, what could i use for that purpose?

Thanks

Leon Barkan
  • 2,676
  • 2
  • 19
  • 43
  • 1
    Possible duplicate of [How might I receive notifications when a USB device is connected?](https://stackoverflow.com/q/771205/11683) – GSerg Oct 07 '18 at 07:00
  • @GSerg - it could help, thanks – Leon Barkan Oct 07 '18 at 07:03
  • [Posted a few days ago](https://stackoverflow.com/questions/52598371/catch-usb-plug-and-unplug-event-system-invalidcastexception?answertab=active#tab-top). A bit more complex code than what's in the link proposed by GSerg. When you are notified that a USB device is removed, you need to Close/Dispose all the handles you have opened there (and manage the exceptions). Then, when you are notified that the USB drive is re-inserted, start over. – Jimi Oct 07 '18 at 07:50
  • I need to know what to dispose, there are more than one USB devices inserted – Leon Barkan Oct 07 '18 at 08:05
  • 1
    Don't you know on what device you opened a handle? – Jimi Oct 07 '18 at 09:25
  • 1
    There are a couple of bad mistakes in the code you got from that link. The worst is inserting `base.WndProc(ref m);` `after switch ((WM)m.Msg)`. This will render mute any result. The, you have to identify the type of message. A bunch of different states are passed in `wParam`. You're interested in `uint DBT_DEVICEARRIVAL = 0x8000;` and `uint DBT_DEVICEREMOVECOMPLETE = 0x8004;`. `lParam` will report: **1)** the device type (you're probably interested in `uint DBT_DEVTYP_VOLUME = 0x0002;`) **2)** the Logical Disk ID (the drive letter) => `int DeviceType = Marshal.ReadInt32(m.LParam, 4);` (...) – Jimi Oct 07 '18 at 19:32
  • 1
    => `uint DeviceIDNumber = Marshal.ReadInt32(m.LParam, 12);` `char DeviceLetter = (char)(65 + (int)Math.Log(DeviceIDNumber , 2));` You could use the code in the question I linked (tested & working). Plus, get details on the USB device: [Get serial number of usb storage device](https://stackoverflow.com/questions/49118708/get-serial-number-of-usb-storage-device-in-net-core-2-1?answertab=active#tab-top). If you think you need the `WndProc` detection style code written down, let me know. – Jimi Oct 07 '18 at 19:32

1 Answers1

0

one of the solutions option

public partial class Form1 : Form
{

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }

    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:

                var usbDevices = GetUSBDevices();
                txtInfo.Text = string.Empty;

                foreach (var usbDevice in usbDevices)
                {
                    if (usbDevice.Name.Contains("Name of my usb device"))
                    {
                        // Code ..
                    }
                }
                break;
        }
        base.WndProc(ref m);
    }

    static List<USBDeviceInfo> GetUSBDevices()
    {
        List<USBDeviceInfo> devices = new List<USBDeviceInfo>();

        ManagementObjectCollection collection;
        using (var searcher = new ManagementObjectSearcher(@"Select * From Win32_PnPEntity where DeviceID Like ""USB%"""))
            collection = searcher.Get();

        foreach (var device in collection)
        {
            devices.Add(new USBDeviceInfo(
            (string)device.GetPropertyValue("Name"),
            (string)device.GetPropertyValue("DeviceID"),
            (string)device.GetPropertyValue("PNPDeviceID"),
            (string)device.GetPropertyValue("Description")
            ));
        }

        collection.Dispose();
        return devices;
    }
}

class USBDeviceInfo
{
    public string Name { get; private set; }
    public string DeviceID { get; private set; }
    public string PnpDeviceID { get; private set; }
    public string Description { get; private set; }

    public USBDeviceInfo(string name, string deviceID, string pnpDeviceID, string description)
    {
        this.Name = name;
        this.DeviceID = deviceID;
        this.PnpDeviceID = pnpDeviceID;
        this.Description = description;
    }
}
Leon Barkan
  • 2,676
  • 2
  • 19
  • 43