Thursday, January 3, 2008

WM_DEVICECHANGE problem

In one our Projects at company, we used WM_DEVICECHANGE message to detect the arrival and removal of USB devices. The application was supposed to run on a machine in which will be running along with several other utility applications. Some months after the project delivery, client reported that, sometimes even if a USB device is plugged in, it is not detected. Problem problem.....

After some investigations we found that if we make the window a top-level window (HWND_TOPMOST), there is no such problems. But what’s the relation between the z-order and the above problem. Later we got few more points to identify the relation.

1. The WM_DEVICECHANGE is send to all the top-level windows according to their z-order. That is the window at the top most position receives the message first, then only the window below it and so one.
2. If a window got a WM_DEVICECHANGE and if it didn’t process the message with in a period (in my machine I think it was 20 secs), the message will not reach to the subsequent windows under it.

Now everything became clear to us, some window whose z-order is greater than our application window might have hung or didn’t process the message within 20 seconds. Thus our window didn’t get a chance. Also when we made our window top level it will be one of the first window's to get WM_DEVICECHANGE message so reducing the number of windows above it to get hung. How ever we didn't find a proper solution for this and moved to an alternative method to detect device arrival and removal.

I think windows might not be using the BroadcastSystemMessage() function with the BSF_FORCEIFHUNG flag, while sending the WM_DEVICECHANGE message.