Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capturing laptop lid closing event in windows?

Tags:

windows

I am looking for a way to intercept the laptop lid closing event. In windows 7, the power management allows me to select a desired behavior when the lid is closed. So there must be a way windows knows when the lid is closed.

I did my research, but only found suggestions to monitor the sleep event. I would like to be more specific to only respond to lid closing.

Does anyone have a suggestion?

Thanks!

like image 936
Bear of the Year Avatar asked Dec 20 '10 03:12

Bear of the Year


1 Answers

The question refers to GUID_LIDSWITCH_STATE_CHANGE not to GUID_LIDCLOSE_ACTION.

GUID_LIDCLOSE_ACTION monitors if the user changes the power behavior when the lid is closing (Control Panel -> Power Settings -> Choose what the close lid does)

If you want to monitor the event of lid close/open, you need to register for GUID_LIDSWITCH_STATE_CHANGE. I used it a Windows service:

int ServiceMain(int argc, char** argv)
{
    serviceStatusHandle = RegisterServiceCtrlHandlerExA(serviceName, (LPHANDLER_FUNCTION_EX) ServiceControlHandler, 0);
    ...
    lidcloseRegHandle = RegisterPowerSettingNotification(serviceStatusHandle, &GUID_LIDSWITCH_STATE_CHANGE, DEVICE_NOTIFY_SERVICE_HANDLE);
    ...
}

And in service control handler:

/**
* Event handler for windows service.
*/
void WINAPI ServiceControlHandler(DWORD controlCode, DWORD evtype, PVOID evdata, PVOID Context)
{
    switch (controlCode)
    {...
         case SERVICE_CONTROL_POWEREVENT:
         WriteToLog("Service Control: SERVICE_CONTROL_POWEREVENT builds and fwd the msg");
         msg.control = SERVICE_CONTROL_POWEREVENT;
         msg.event_type = (int) evtype;
         msg.event_data = evdata;
     ...
    }
}

evtype is PBT_POWERSETTINGCHANGE and in evdata you have the event logged: 0 for closed and 1 for opened.

More details here: https://msdn.microsoft.com/en-us/library/aa372723.aspx https://msdn.microsoft.com/en-us/library/hh769082(v=vs.85).aspx

like image 124
Stefan Avatar answered Sep 20 '22 02:09

Stefan