0
我已经从控制台应用程序获得了一些代码,我编写了这个即时通讯程序以适应在基于UI的应用程序中的使用。它注册一个事件陷阱来监视系统范围内的鼠标移动。有人建议我创建并运行一个线程来设置事件循环,所以我不阻止应用程序(代码从applicationDidFinishLaunching调用)。在用户界面应用程序中使用CFRunLoop
我必须说实话,我已经看了大约运行循环和IM完全糊涂了:-(我的代码只是在调用listen
功能挂着几个文件。
static MouseListener* listener = nil;
CGEventRef eventOccurred(CGEventTapProxy proxy, CGEventType type, CGEventRef event, void* refcon) {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
event = [listener eventOccurred:proxy:type:event:refcon];
[pool release];
return event;
}
@implementation MouseListener
-(MouseListener*) myinit {
if (self = [super init]) {
eventThread = [[NSThread alloc] initWithTarget:self
selector:@selector(listen:)
object:nil];
[eventThread start];
}
return self;
}
-(void)listen:(NSObject*) object {
if (!listener) {
listener = self;
CFMachPortRef tap = CGEventTapCreate(kCGHIDEventTap,
kCGHeadInsertEventTap,
kCGEventTapOptionDefault,
NSAnyEventMask,
eventOccurred,
NULL);
if (tap) {
CFRunLoopRef loop = CFRunLoopGetCurrent();
CFRunLoopSourceRef src = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, tap, 0);
CFRunLoopAddSource(loop, src, kCFRunLoopCommonModes);
CGEventTapEnable(tap, true);
//CFRunLoopRun();
//[[NSRunLoop currentRunLoop] run];
CFRelease(src);
CFRelease(tap);
}
}
}
-(CGEventRef) eventOccurred:(CGEventTapProxy) proxy: (CGEventType) type: (CGEventRef) event: (void*) refcon {
// Do stuff, never gets called
return event;
}