This answer provides relevant code examples for detecting USB devices to remove or add:
using System; using System.Runtime.InteropServices; internal static class UsbNotification { public const int DbtDevicearrival = 0x8000;
Use from a WPF window:
protected override void OnSourceInitialized(EventArgs e) { base.OnSourceInitialized(e); // Adds the windows message processing hook and registers USB device add/removal notification. HwndSource source = HwndSource.FromHwnd(new WindowInteropHelper(this).Handle); if (source != null) { windowHandle = source.Handle; source.AddHook(HwndHandler); UsbNotification.RegisterUsbDeviceNotification(windowHandle); } } /// <summary> /// Method that receives window messages. /// </summary> private IntPtr HwndHandler(IntPtr hwnd, int msg, IntPtr wparam, IntPtr lparam, ref bool handled) { if (msg == UsbNotification.WmDevicechange) { switch ((int)wparam) { case UsbNotification.DbtDeviceremovecomplete: Usb_DeviceRemoved(); // this is where you do your magic break; case UsbNotification.DbtDevicearrival: Usb_DeviceAdded(); // this is where you do your magic break; } } handled = false; return IntPtr.Zero; }
Usage from Windows Forms:
public Form1() { InitializeComponent(); UsbNotification.RegisterUsbDeviceNotification(this.Handle); } protected override void WndProc(ref Message m) { base.WndProc(ref m); if (m.Msg == UsbNotification.WmDevicechange) { switch ((int)m.WParam) { case UsbNotification.DbtDeviceremovecomplete: Usb_DeviceRemoved();
source share