本文介绍了监听OS X中的电源按钮事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

按下电源按钮时,将显示以下对话框,并且如果发出此通知,则该通知:

When the power button is pressed I am presented with the following dialogue box, and this notification if dispatched:

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

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

fyi:

我设法破解了一个Objective C代码段,该代码段是这样做的:

I have managed to hack together an Objective C snippet which does this:

#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];
    }

}

推荐答案

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

a simple c++ SCCE would look like:

#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 进行编译.

如何将其挂接到自己的应用程序中完全是另一回事.

How you hook it into your own application is another matter entirely.

这篇关于监听OS X中的电源按钮事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 11:37