1

Is it possible to handle click event on menu bar in OS X?

I mean white space, not menu item.

I tried this - 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;
}];

Also I tried addGlobalMonitorForEventsMatchingMask.

Without any result. Is it possible?

Thanks.

Community
  • 1
  • 1
stosb
  • 13
  • 1
  • 3

1 Answers1

0

You can use an event tap to track mouse events globally and then just calculate whether the click is within the rect you want:

#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);
    }
}
Guilherme Rambo
  • 2,018
  • 17
  • 19
  • But how I should know what user clicked in white space? – stosb Sep 13 '15 at 19:16
  • 1
    May I ask why you need this? Btw, the code I provided is what you want, you just have to adapt It to your needs... – Guilherme Rambo Sep 14 '15 at 15:03
  • I had to change the third argument passed into `CGEventTapCreate` from `0` to one of the `CGEventTapOptions` enum values to get it to compile, but otherwise this seems to be working well for me. – Rich Apr 12 '21 at 14:24