我想监视 OSX 盒子上的屏幕保护程序和锁屏事件。作为第一遍,我可以将它们打印到控制台。
根据另一个问题的建议,我编写了一些 Objective C 来监听
com.apple.screensaver.didstart
、com.apple.screensaver.didstop
、com.apple.screenIsLocked
和com.apple.screenIsUnlocked
事件的 Cocoa 通知。
// ScreenSaverMonitor.h
#import <Foundation/NSObject.h>
#import <Foundation/NSNotification.h>
@interface ScreenSaverMonitor: NSObject {}
-(id) init;
-(void) receive: (NSNotification*) notification;
@end
// ScreenSaverMonitor.m
#import "ScreenSaverMonitor.h"
#import <Foundation/NSString.h>
#import <Foundation/NSDistributedNotificationCenter.h>
#import <Foundation/NSRunLoop.h>
#import <stdio.h>
@implementation ScreenSaverMonitor
-(id) init {
NSDistributedNotificationCenter * center
= [NSDistributedNotificationCenter defaultCenter];
[center addObserver: self
selector: @selector(receive:)
name: @"com.apple.screensaver.didstart"
object: nil
];
[center addObserver: self
selector: @selector(receive:)
name: @"com.apple.screensaver.didstop"
object: nil
];
[center addObserver: self
selector: @selector(receive:)
name: @"com.apple.screenIsLocked"
object: nil
];
[center addObserver: self
selector: @selector(receive:)
name: @"com.apple.screenIsUnlocked"
object: nil
];
printf("running loop... (^C to quit)");
[[NSRunLoop currentRunLoop] run];
printf("...ending loop");
return self;
}
-(void) receive: (NSNotification*) notification {
printf("%s\n", [[notification name] UTF8String] );
}
@end
// ScreenSaverMonitorMain.m
#import "ScreenSaverMonitor.h"
int main( int argc, char ** argv) {
[[ScreenSaverMonitor alloc] init];
return 0;
}
它编译得很好,但是当我运行它时,我似乎没有观察到任何屏幕保护程序事件(尽管屏幕保护程序多次出现):
% gcc -Wall ScreenSaverMonitor.m ScreenSaverMonitorMain.m -o ScreenSaverMonitor -lobjc -framework Cocoa
% ./ScreenSaverMonitor
running loop (^C to quit)...
^C
%
我的 Objective C 和 Cocoa 知识非常生疏,所以我不确定我是否使用错误的框架,或者我是否注册了错误的事件(也不知道在哪里查找这些是否是正确的事件或不是)。
那么我做错了什么?