C++ 在OSX中侦听电源按钮事件
按下电源按钮时,我会看到以下对话框,如果发出此通知:C++ 在OSX中侦听电源按钮事件,c++,macos,C++,Macos,按下电源按钮时,我会看到以下对话框,如果发出此通知: \uuu CFNotification 0x10011f410{name=com.apple.logoutInitiated;object=501} 强>问题:如何从C++应用程序中侦听和处理这个事件? < /p> 供参考: 我成功地拼凑了一个Objective C代码段,它实现了以下功能: #import "AppDelegate.h" @implementation AppDelegate - (void)applicationDi
\uuu CFNotification 0x10011f410{name=com.apple.logoutInitiated;object=501}
<>强>问题:如何从C++应用程序中侦听和处理这个事件?<强> < /p>
供参考:
我成功地拼凑了一个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];
}
}
本质上,您希望访问
NSDistributedNotificationCenter
环绕的底层功能
也许你应该更具体地看一看
这些不是C++本身,它们是C函数,但可以从C++调用它们。
< P> <代码> Copeoundation < /Cord>有一个用C编写的好API,因此可以使用<代码> CFNoTimeCcTcCuto Advestue>代码>函数,并将C++程序链接到必要的框架。例如:clang++ <your options> -framework CoreFoundation
clang++-frameworkcorefoundation
看。这里的快速搜索显示: < P>简单的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;
}
#包括
#包括
无效的
myCallBack(CFNotificationCenterRef中心,
无效*观察员,
CFStringRef名称,
const void*对象,
CFDictionaryRef用户信息){
std::如果我错了,就不能纠正我,但我相信上面的代码不会拦截,而只是侦听通知。(细微差别是,“侦听”允许您将通知隐藏到其他可能也在侦听它的进程。)是的,抱歉,没有拦截需要,只是听和行动这样的事件。你的C++代码是在一个MAC应用程序还是命令行实用程序?@ TROJANFOE,我没看到它如何改变任何东西。@ QwertyBob没有,但我只是试图理解可能适用于可能的解决方案的限制。