是否可以在OS X中的菜单栏上处理点击事件?

时间:2015-08-06 18:11:02

标签: macos cocoa menubar

是否可以在OS X中的菜单栏上处理点击事件?

我指的是白色空间,而不是菜单项。

我试过了 - Detect click on OS X menu bar? - addLocalMonitorForEventsMatchingMask

[NSEvent addLocalMonitorForEventsMatchingMask: (NSLeftMouseDownMask | NSRightMouseDownMask | NSOtherMouseDownMask | NSKeyDownMask) handler:^(NSEvent *incomingEvent) {
    NSEvent *result = incomingEvent;
    NSWindow *targetWindowForEvent = [incomingEvent window];
    return result;
}];

我还尝试了addGlobalMonitorForEventsMatchingMask。

没有任何结果。有可能吗?

感谢。

1 个答案:

答案 0 :(得分:-1)

您可以使用事件点按来全局跟踪鼠标事件,然后只计算点击是否在您想要的矩形内:

#define kMenuBarHeight 22.0
CGEventRef leftMouseTapCallback(CGEventTapProxy aProxy, CGEventType aType, CGEventRef aEvent, void* aRefcon)
{
    CGPoint theLocation = CGEventGetLocation(aEvent);
    if (theLocation.y <= kMenuBarHeight) {
        NSLog(@"CLICKED THE MENUBAR");
    }

    return aEvent;
}

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
    CGEventMask mask = CGEventMaskBit(kCGEventLeftMouseDown) | CGEventMaskBit(kCGEventLeftMouseUp);

    CFMachPortRef leftMouseEventTap = CGEventTapCreate(kCGSessionEventTap, kCGHeadInsertEventTap, 0, mask, leftMouseTapCallback, NULL);

    if (leftMouseEventTap) {
        CFRunLoopSourceRef runLoopSource = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, leftMouseEventTap, 0);

        CFRunLoopAddSource(CFRunLoopGetCurrent(), runLoopSource, kCFRunLoopCommonModes);
        CGEventTapEnable(leftMouseEventTap, true);
    }
}