USB power status detection

Windows provides the ability to disable certain peripheral devices, such as USB ports, to save power (this behavior can be enabled / disabled using the device manager). The power turns off under various conditions, such as when the lid of a laptop is closed. This causes me a problem, since I have a GUI that talks about connecting to the USB port of the equipment, and the connection is disconnected every time the laptop lid closes. Is there a way to programmatically detect this power off event (standby?) Before it occurs and more gracefully disconnect my USB device? Is there a way to programmatically configure each of the system's USB ports to disable this behavior?

Now I am looking at SystemEvents.PowerModeChanged , is this the right event to detect this?

+6
source share
2 answers

Looks like you want

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

First you need to call RegisterPowerSettingNotification, then your WM_POWERBROADCAST messages will be received by your application.

This page has a C # implementation of the power management class using these window messages. http://www.koders.com/csharp/fid00BAA34B0CAA3E320F9F5A44610A015973BF28ED.aspx?s=nativemethods#L175

+1
source

As mentioned by previous posters, RegisterPowerSettingNotification is what you want. To clarify, you can refer to Winforms (System.Windows.Forms.dll) for other types of .NET applications (console, etc.). You can access the window handle (for receiving messages) by subclassing Winform (the Forms class) and overriding WndProc.

MSDN has a very good article on how to do this, as well as sample code.

+1
source

Source: https://habr.com/ru/post/887283/


All Articles