Skip to content

Instantly share code, notes, and snippets.

@Akira-Hayasaka
Last active January 7, 2019 16:47
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Akira-Hayasaka/863ff80c2d95c7ca1572 to your computer and use it in GitHub Desktop.
Save Akira-Hayasaka/863ff80c2d95c7ca1572 to your computer and use it in GitHub Desktop.
get osx power button pressed
//
// PowerButtonDetector.h
// BootManager
//
// Created by Akira on 4/7/15.
//
//
#ifndef BootManager_PowerButtonDetector_h
#define BootManager_PowerButtonDetector_h
#include "ofMain.h"
static const string shutdonwScript = "osascript -e \'tell app \"System Events\" to shut down\'";
static void onPwrBtnPressed(CFNotificationCenterRef center,
void *observer,
CFStringRef name,
const void *object,
CFDictionaryRef userInfo)
{
ofLog() << "Power Button Pressed";
ofSystem(shutdonwScript);
}
class PowerButtonDetector : public ofThread
{
public:
void setup()
{
state = INIT;
startThread();
}
void exit()
{
waitForThread();
}
protected:
void threadedFunction()
{
while(isThreadRunning())
{
if (state == INIT && lock())
{
CFNotificationCenterRef distCenter;
CFStringRef evtName = CFSTR("com.apple.shutdownInitiated");
distCenter = CFNotificationCenterGetDistributedCenter();
if (NULL == distCenter)
return 1;
CFNotificationCenterAddObserver(distCenter, NULL, &onPwrBtnPressed, evtName, NULL, CFNotificationSuspensionBehaviorDeliverImmediately);
CFRunLoopRun();
state = RUN;
unlock();
}
}
}
private:
enum STATE
{
INIT,
RUN
};
STATE state;
};
#endif
@stephanschulz
Copy link

stephanschulz commented Jan 7, 2019

thanks for putting this together. it's very helpful.

I found running this shell script through apple script shut the system down too.

static const string shutdonwScript = "osascript -e 'do shell script \"sudo /sbin/shutdown -h now\"'";

@stephanschulz
Copy link

Would you know how to set a global variable inside onPwrBtnPressed or anywhere else so that i can trigger other code events instead of shutdown?
Since it is a static function I'm not able to simply set a global variable.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment