【问题标题】:Is it possible to handle click event on menu bar in OS X?是否可以在 OS X 中处理菜单栏上的单击事件?
【发布时间】:2015-09-12 10:49:39
【问题描述】:

是否可以在 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。

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

谢谢。

【问题讨论】:

    标签: macos cocoa menubar


    【解决方案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);
        }
    }
    

    【讨论】:

    • 但是我怎么知道用户在空白处点击了什么?
    • 请问您为什么需要这个?顺便说一句,我提供的代码是你想要的,你只需要适应你的需要......
    • 我必须将传递给CGEventTapCreate 的第三个参数从0 更改为CGEventTapOptions 枚举值之一才能编译,但否则这似乎对我来说效果很好。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-20
    • 1970-01-01
    相关资源
    最近更新 更多