Detecting USB power state
Asked Answered
C

2

7

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?

Clap answered 4/5, 2011 at 14:17 Comment(0)
M
1

It sounds like you want

  1. WM_POWERBROADCAST (http://msdn.microsoft.com/en-us/library/aa373247(v=vs.85).aspx)
  2. RegisterPowerSettingNotification (http://msdn.microsoft.com/en-us/library/aa373196.aspx)

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

Metalliferous answered 4/5, 2011 at 14:36 Comment(3)
How do I go about getting to those messages from a non-WinForms C# class?Clap
Have updated the answer a bit. I've not actually done this but I would assume you can subscribe to RegisterPowerSettingNotification from any classMetalliferous
@LightWing - that question has no relation to this one, unless you're referring to the link posted to the LibUSBdotNET project link posted in one of the answers. Does that have built in functionality to for this kind of event?Clap
A
1

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.

Anything answered 8/9, 2011 at 9:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.