Sleep/Wake Events in OS X

In case you wish for certain events to take place on sleep or wake of you Mac, the software sleepwatcher is your friend. You can install it from Macports with the following line:

sudo port install sleepwatcher

To launch it on system startup, do this:

sudo port load sleepwatcher

If e.g. you want to show a login window on wakeup, create an executable file called ~/.sleep with the following contents:

/System/Library/CoreServices/Menu\ Extras/User.menu/Contents/Resources/CGSession -suspend

Update on 10/10/2015: The latter doesn’t work anymore. You’d need your own binary accessing the locking feature of Apple’s Keychain. The source code is like this:

\#import <objc/runtime.h>
\#import <Foundation/Foundation.h>

int main () {
    NSBundle *bundle = [NSBundle bundleWithPath:@"/Applications/Utilities/Keychain Access.app/Contents/Resources/Keychain.menu"];

    Class principalClass = [bundle principalClass];

    id instance = [[principalClass alloc] init];

    [instance performSelector:@selector(_lockScreenMenuHit:) withObject:nil];

    return 0;
}

Save this as =lockscreen-main.m= and compile it with

clang -framework Foundation lockscreen-main.m -o lockscreen

Leave a Comment