c# receive plug and play events

1.7k views Asked by At

I was wondering if there are any examples and/or documentation on how to handle Plug and Play event messages used in Windows. Ideally what I am trying to accomplish is to be able to have my application detect a device that has been connected to a machine without having to have a timer, that on tick, will poll ALL COM ports. I find that doing this is extremely inefficient and ramps up my application's CPU usage ten fold. My application is in C# and is currently leveraging .NET 4.0 we are looking to upgrade to .NET 4.5 within the next month. So I am reaching out to find some kind of literature on how to do this. As this is my fist look into supporting a plug and play devices please be gentle with the criticism.

EDIT: Also this application will be running on Windows 7 and Windows XP

1

There are 1 answers

1
Harrison Paine On BEST ANSWER

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