我已经从我写的一个控制台应用程序中获得了一些代码,我试图适应在基于UI的应用程序中使用。它注册一个事件陷阱来监控系统范围内的鼠标移动。有人建议我创建并运行一个线程来设置事件循环,这样我就不会阻塞应用程序(代码是从applicationDidFinishLaunching调用的)。
老实说,我看过一些关于运行循环的文档,我完全搞混了:-(我的代码只是挂在对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;
}发布于 2011-02-22 19:58:02
回到家后,我需要检查我的代码,但您的代码看起来没问题(我也做过类似的检查,但改为侦听I/O Kit事件)。CFRunLoopRun()是你想要调用的函数,但是,你为什么不把你的事件点击添加到你的应用程序的主运行循环中呢?这也避免了任何线程恶作剧。
https://stackoverflow.com/questions/5022518
复制相似问题