I've accomplished this in the past when writing a file browser by using a dummy HwndSource
and adding an event handler via the HwndSource.AddHook()
method.
// In object constructor
var hwndSource = new HwndSource(0, 0, 0, 0, 0, "", IntPtr.Zero); // Set up dummy HwndSource
hwndSource.AddHook(sourceHook);
IntPtr sourceHook(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
if (msg = WM_DEVICECHANGE)
if (wParam.ToInt32 == DBT_DEVICEARRIVAL) // Do what you need to do
if (wParam.ToInt32 == DBT_DEVICEREMOVALCOMPLETE) // Handle device removal
}
// Uses these defined constants:
private const int WM_DEVICECHANGE = 0x219;
private const int DBT_DEVICEARRIVAL = 0x8000;
private const int DBT_DEVICEREMOVALCOMPLETE = 0x8004;
The MSDN for WM_DEVICECHANGE also has info for other const definitions that may be useful: http://msdn.microsoft.com/en-us/library/windows/desktop/aa363480(v=vs.85).aspx