2011-02-16 23 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太

相關問題