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