2011-02-16 24 views
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; 
} 

回答

0

我需要在我回家后检查我的代码,但是你看起来没问题(我已经做了类似的事情,但是监听I/O Kit事件)CFRunLoopRun()是你想调用的函数,但是,为什么你只需将你的事件点击添加到你的应用程序的主要runloop?这可以节省任何线程shenanigans太

相关问题