1

我想在 Mac os 中捕获鼠标右键和左键单击并使用以下代码:


CGEventRef event = CGEventCreate(NULL);
CGEventType eventType = CGEventGetType(event);

cout << "mouse event type is : " << eventType << endl;

我使用此代码查看 eventType 例如必须是 kCGEventLeftMouseDown 或显示事件类型的整数值,但此代码不捕获鼠标事件并返回 0

4

1 回答 1

2

这应该怎么做:D 你需要捕获现有事件......你只需调用一个助手并制作一个新事件......但这很简单。

看看CGEventTap你想要什么。

鉴于操作系统启用了可访问性,事件水龙头在系统范围内工作!


一些代码:

//called for each event
static CGEventRef myCGEventCallback(CGEventTapProxy proxy, 
                                        CGEventType t,
                                        CGEventRef event,
                                        void *refcon);

- (void)threaded_listenForDrags {
    if (!_eventTap)
    {
        int eventMask = CGEventMaskBit(kCGEventLeftMouseDown)
        | CGEventMaskBit(kCGEventLeftMouseUp) 
        | CGEventMaskBit(kCGEventLeftMouseDragged)
        | CGEventMaskBit(kCGEventRightMouseDragged)
        | CGEventMaskBit(kCGEventOtherMouseDragged);

        _eventTap = CGEventTapCreate(kCGHIDEventTap,
                                    kCGHeadInsertEventTap,
                                    kCGEventTapOptionListenOnly, 
                                    eventMask, 
                                    myCGEventCallback,
                                    (__bridge void*)self);
        if (!_eventTap)
        {
            DDLogError(@"%@ no tap; universal access?", NSStringFromSelector(_cmd));
            return;
        }
        CFRunLoopSourceRef runLoopSource = CFMachPortCreateRunLoopSource(NULL,
                                                                         _eventTap, 0);
        CFRunLoopAddSource(CFRunLoopGetCurrent(), runLoopSource, 
                           kCFRunLoopCommonModes);

        CFRelease(runLoopSource);       
    }
    CGEventTapEnable(_eventTap, true);

    CFRunLoopRun();
}

- (void)threaded_endListenForDrags {
    CFMachPortRef et = _eventTap;

    CGEventTapEnable(_eventTap, false);
    _eventTap = nil;

    dispatch_sync(dispatch_get_main_queue(), ^{
        if(_enabled) {
            _enabled = NO;
            [self setEnabled:YES];
        }
    }); 

    CFRunLoopStop(CFRunLoopGetCurrent());
    CFRelease(et);
}
于 2013-04-07T09:03:29.707 回答