Is there any way to execute something when closing the laptop's lid?

I'm wondering if there is any way to execute a program, run some command or anything else when closing the laptop's lid.
My question aims to be generic, both for Windows and Linux. Something useful should be locking the laptop when closing the lid (Win + L in windows), or running expensive processes such as antivirus analysis etc. without doing it manually before closing the lid.


Solution 1:

In Windows 7, the only options you have for performing actions when you close the lid are in Power Options in the Control Panel. Available actions are:

  • Do nothing
  • Sleep
  • Hibernate
  • Shut down

You cannot create custom actions here to assign to the lid close event.

But!

You can use the Task Scheduler to schedule a task when a certain event is logged. Going to sleep is a logged event. You can specify, when you create the scheduled task, that you want the computer to wake from sleep to perform the task.

Detailed instructions here: Task scheduler on laptop lid close?

Solution 2:

There's a fairly lengthy and detailed tutorial on how to execute scripts when you close/open your laptop lid on Ubuntu forums.

I can't seem to find anything to emulate the same under Windows, however.

Solution 3:

Solution

Make 'AwayModeEnabled' and Windows won't actually go to sleep when it goes to sleep. Then use the Task Schedule hack mentioned by William above.

Pros

Don't lose network connections

Cons

Your computer can never really go off when sleeping

Howto

From User log-in screen activation

regedit....HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SessionManager\Power, add a new DWORD32 there and rename it as AwayModeEnabled, right click and edit the value as 1 (Hex). Finally, edit the laptop's Lid close action as Sleep on the Power Option setting page in Windows7.

Testing My Windows 7 laptop with an open ssh connection.