Question

I have a full-screen transparent window that displays above the main menu of my app. It has ignoresMouseEvents set to NO. To receive mouse clicks nonetheless, I added this code :

[NSEvent addLocalMonitorForEventsMatchingMask:NSLeftMouseDownMask handler:^(NSEvent *event) {
    [self click:event];
    return event;
}];

Every time the user clicks while my app is active, a method click is thus called :

- (BOOL)click:(NSEvent *)event {
    NSPoint coordinate = [event locationInWindow];
    float ycoord = coordinate.y;
    float menuheight = [[NSApp mainMenu] menuBarHeight];
    float windowheight = [[NSApp mainWindow] frame].size.height;
    if (ycoord >= windowheight - menuheight && ![[NSApp mainWindow] ignoresMouseEvents]) {
        [[NSApp mainWindow] setIgnoresMouseEvents:YES];
        [NSApp sendEvent:event];
        NSLog(@"click");
        [[NSApp mainWindow] setIgnoresMouseEvents:NO];
        return YES;
    }
    return NO;
}

As you can see, it changes the ignoresMouseEvents property of the main window to YES if the click was on the main menu bar - after which it calls sendEvent: in NSApplication. Finally it changes the ignoresMouseEvents property of the main window back to NO.

However, even though the log does say 'click' when the main menu bar is clicked, the click has no effect. If I click a menu item (eg. the 'File' menu item), for example, it will not open the corresponding menu (in this case the file menu).

What am I doing wrong?

Was it helpful?

Solution

The window that an event is targeted toward is decided by the window server before your app even receives it. It is not decided at the time of the call to -sendEvent:. The primary effect of -setIgnoresMouseEvents: is to inform the window server, not Cocoa's internals, how to dispatch mouse events.

Except for something like event taps, once you've received an event, it's too late to re-target it.

Note, for example, that the NSEvent already has an associated -window before your call to -sendEvent:. -sendEvent: is just going to use that to dispatch it.

If you want to allow clicks in the menu bar, you should either size your window so it doesn't overlap the menu bar or you should set its window level to be behind the menu bar.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top