Reputation: 13140
Windows has the option of powering down certain peripherals, such as USB ports, to save power (this behavior can be enabled/disabled via Device Manager). The power down happens under various conditions such as when the lid of a laptop is closed. This is causing a problem for me as I have a GUI which talks to hardware attached to the USB port and communications are severed every time the laptop lid is closed. Is there a way to programmatically detect this power-down (standby?) event before it happens and more gracefully shut down my USB device? Is there a way to programmatically configure each of the system’s USB ports to disable this behavior?
Right now I'm looking at SystemEvents.PowerModeChanged
, is this the right event to detect this?
Upvotes: 7
Views: 2960
Reputation: 1249
As mentioned by the previous posters RegisterPowerSettingNotification is what you want. To clarify, you can reference Winforms (System.Windows.Forms.dll) from other types of .NET applications (console, etc). You can get access to a Window handle (in order to receive messages) by subclassing a Winform (the Forms class) and overriding its WndProc.
MSDN has a very good article of doing just that, along with example code.
Upvotes: 1
Reputation: 17392
It sounds like you want
You first need to call RegisterPowerSettingNotification then WM_POWERBROADCAST messages will be received by your application.
This page has a c# implementation of a power management class using these window messages. http://www.koders.com/csharp/fid00BAA34B0CAA3E320F9F5A44610A015973BF28ED.aspx?s=nativemethods#L175
Upvotes: 1