在OS X中侦听电源按钮事件

时间:2013-10-30 13:31:27

标签: c++ macos

按下电源按钮后,我会看到以下对话框,如果已发送此通知:

__CFNotification 0x10011f410 {name = com.apple.logoutInitiated; object = 501}

enter image description here

问题:如何从C ++应用程序中监听此事件并采取相应措施?

供参考:

我设法破解了一个Objective C片段,它实现了这个目的:

#import "AppDelegate.h"

@implementation AppDelegate

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    // Insert code here to initialize your application

    @autoreleasepool
    {
        [[NSDistributedNotificationCenter defaultCenter]
         addObserverForName: nil
         object: nil
         queue: [NSOperationQueue mainQueue]
         usingBlock: ^(NSNotification *notification) {

             //The event notification we are looking for:
             //__CFNotification 0x10011f410 {name = com.apple.logoutInitiated; object = 501}

             NSString *event = notification.name;
             BOOL res = [event isEqualToString:@"com.apple.logoutInitiated"];
             if (res)
             {
                 printf("POWER BUTTON PRESSED");
             }
             else
             {
                 printf("IGNORE");
             }
         }];

        [[NSRunLoop mainRunLoop] run];
    }

}

3 个答案:

答案 0 :(得分:2)

一个简单的c ++ SCCE看起来像:

#include <iostream>
#include <CoreFoundation/CoreFoundation.h>

void
myCallBack(CFNotificationCenterRef center,
           void *observer,
           CFStringRef name,
           const void *object,
           CFDictionaryRef userInfo) {
    std::cout << "Power Button Pressed" << std::endl;
}

int
main(int argc, const char * argv[])
{
    CFNotificationCenterRef distCenter;
    CFStringRef evtName = CFSTR("com.apple.logoutInitiated");
    distCenter = CFNotificationCenterGetDistributedCenter();
    if (NULL == distCenter)
        return 1;
    CFNotificationCenterAddObserver(distCenter, NULL, &myCallBack, evtName, NULL, CFNotificationSuspensionBehaviorDeliverImmediately);
    CFRunLoopRun();
    return 0;
}

并将使用clang++ -framework CoreFoundation testfile.cpp进行编译。

如何将它挂钩到您自己的应用程序中完全是另一回事。

答案 1 :(得分:0)

基本上,您希望访问NSDistributedNotificationCenter包含的基础功能。

也许你应该看CFNotificationCenterRef,更具体地说CFNotificationCenterGetDistributedCenter()

这些不是C ++本身,它们是C函数,但你可以用C ++调用它们。

答案 2 :(得分:0)

CoreFoundation有一个用C编写的很好的API,因此你可以使用CFNotificationCenterAddObserver函数并将你的C ++程序链接到必要的框架。例如:

clang++ <your options> -framework CoreFoundation

请参阅official documentation。这里的快速搜索显示an example of how to use it