How to detect and disable power button event in Windows 7 from laptop

On Windows XP, I can detect an event when the laptop's power button is pressed. Condition for receiving APMQUERYSUSPEND event - [control panel → power option-> system setting-> when I press power button → sleep] should be changed to "Sleep".

MainFrm::OnPowerBroadcast(WPARAM wParam, LPARAM lParam)

      

{

         switch (wParam)

         {

                       case PBT_APMQUERYSUSPEND:

                       // Ask question whether to power off or not

                       // If not, return BROADCAST_QUERY_DENY

                       return BROADCAST_QUERY_DENY;

         }

      

But from windows 7 I have no clue to detect the event. Based on windows 7, the APMQUERYSUSPEND event has been removed. Even though I tried the SetThreadExecutionState API to block shutdown, the dose doesn't work. http://msdn.microsoft.com/ko-kr/library/windows/desktop/aa372716(v=vs.85).aspx

Do you know any idea to catch the event when the power button is pressed?

Thank.

+3


source to share


1 answer


According to Microsoft documentation, it is no longer possible to interrupt a sleep event after it has started. There's a very informative presentation on Windows Vista / 7 Power Management here . There is another way to capture the sleep event. I will be using C # syntax in my example:

First, call RegisterHotKey(this.Handle, 0, 0x4000, 0x5F)

user32.dll from the API to intercept the sleep key. Then override the method of your program WndProc

(depending on what language and environment you are using, there are different ways to do this) and listen for the 312h hotkey message. Once you get it, call SetThreadExecutionState(EXECUTION_STATE.ES_AWAYMODE_REQUIRED | EXECUTION_STATE.ES_SYSTEM_REQUIRED | EXECUTION_STATE.ES_CONTINUOUS)

from the kernel32.dll API to prevent Windows from triggering a sleep event. After a while (if you want your system to be able to sleep again), you can call SetThreadExecutionState(EXECUTION_STATE.ES_CONTINUOUS)

.

Please note that SetThreadExecutionState

this will have no effect if the sleep routine has already been initiated, so the above cannot be done for the power button, which cannot be plugged in as far as I know (if anyone really knows a way to do this please give me know!) . Probably also, which is why SetThreadExecutionState

didn't work for you.



Constants:

        ES_CONTINUOUS = 0x80000000,
        ES_SYSTEM_REQUIRED = 1,
        ES_AWAYMODE_REQUIRED = 0x00000040

      

+4


source







All Articles