Last active
January 7, 2019 16:47
-
-
Save Akira-Hayasaka/863ff80c2d95c7ca1572 to your computer and use it in GitHub Desktop.
get osx power button pressed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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 |
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
thanks for putting this together. it's very helpful.
I found running this shell script through apple script shut the system down too.