2015-10-17 71 views
0

我目前使用addLocalMonitorForEventsMatchingMask监视鼠标事件,我从主线程调用它。它效果很好。不过,我现在想把它移到主线程。有没有其他的选择,比如像从线程创建一个隐藏的窗口,并做着NSRunLoopaddLocalMonitorForEventsMatchingMask Off-mainthread的替代

我阅读文档:https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/EventOverview/MonitoringEvents/MonitoringEvents.html

的处理器是始终称为主线程。这两个类方法都会返回调用对象不拥有的监视器对象(因此不需要保留或释放)。

有没有其他方法可以从主线程中完成?

我无法在另一个线程的mainthread上设置回调。我正在使用FFI,现在它不具备这一功能。

这里是我的代码的情况下,它可以帮助,但我希望的替代方式为关闭主线程请:

myHandler_js = function(c_arg1__self, objc_arg1__aNSEventPtr) { 

    var cType = ostypes.API('objc_msgSend')(objc_arg1__aNSEventPtr, ostypes.HELPER.sel('type')); 

    cType = ctypes.cast(cType, ostypes.TYPE.NSEventType); 


    return objc_arg1__aNSEventPtr; // return null to block 
}; 
myHandler_c = ostypes.TYPE.IMP_for_EventMonitorCallback.ptr(myHandler_js); 
myBlock_c = ostypes.HELPER.createBlock(myHandler_c); 


var rez_add = ostypes.API('objc_msgSend')(ostypes.HELPER.class('NSEvent'), ostypes.HELPER.sel('addLocalMonitorForEventsMatchingMask:handler:'), ostypes.TYPE.NSEventMask(ostypes.CONST.NSKeyDownMask), myBlock_c.address()); 

回答

0

解决方案是使用CGEventTap

这个人是有问题,但不适更新它,只要它的准备:

GetCurrentProcess(psn); 

var mask = 1 << kCGEventLeftMouseDown | // CGEventMaskBit(kCGEventLeftMouseDown) 
      1 << kCGEventLeftMouseUp | 
      1 << kCGEventRightMouseDown | 
      1 << kCGEventRightMouseUp | 
      1 << kCGEventOtherMouseDown | 
      1 << kCGEventOtherMouseUp | 
      1 << kCGEventScrollWheel; 

mouseEventTap = CGEventTapCreateForPSN(&psn, kCGHeadInsertEventTap, kCGEventTapOptionDefault, mask, null); 

if (!mouseEventTap.isNull()) { 
     aRLS = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, mouseEventTap, 0); 
     CFRelease(mouseEventTap); 

     if (!aRLS.isNull()) { 
      aLoop = CFRunLoopGetCurrent(); 

      CFRunLoopAddSource(aLoop, aRLS, kCFRunLoopCommonModes); 

      CFRelease(aRLS); 
      CFRelease(aLoop); 

      rez = CFRunLoopRunInMode(ostypes.CONST.kCFRunLoopCommonModes, 10, false); // figure out how to make this run indefinitely 
      // rez is 1 :(

     } 

}