Search code examples
cocoanswindownswindowcontroller

Hooking Event at NSWindow


I'm making popup tooltip in NSWindow, like following XCode tooltip

enter image description here

If user press a button, popup is shown. It is easy.

But after that, if user press any button in this window, popup should be hidden.

But if user press button, nswindow's mousedown: isn't be called. so nswindowcontroller can not receive that event.

How can nswindow can detect all event in window's region?


Solution

  • You can create a contextMenu for small window, that opens on your action.

    *NOTE: in the image, that is a custom view, not a contextMenu.*

    - (IBAction)button:(id)sender {
        NSRect frame = [(NSButton *)sender frame];
        NSPoint menuOrigin = [[(NSButton *)sender superview] convertPoint:NSMakePoint(frame.origin.x+80, frame.origin.y+frame.size.height-10)
                                                                   toView:nil];
        NSEvent *event =  [NSEvent mouseEventWithType:NSLeftMouseDown
                                             location:menuOrigin
                                        modifierFlags:NSLeftMouseDownMask // 0x100
                                            timestamp:0.0
                                         windowNumber:[[(NSButton *)sender window] windowNumber]
                                              context:[[(NSButton *)sender window] graphicsContext]
                                          eventNumber:0
                                           clickCount:1
                                             pressure:1];
        NSMenu *menu = [[NSMenu alloc] init];
        [menu setAutoenablesItems:NO];
        [menu insertItemWithTitle:@"Add Favorite"
                           action:@selector(addFavorite:)
                    keyEquivalent:@""
                          atIndex:0];
        [menu insertItem:[NSMenuItem separatorItem] atIndex:1];
        [menu insertItemWithTitle:@"Manage Favorite"
                           action:@selector(manageFavorite:)
                    keyEquivalent:@""
                          atIndex:2];
          [NSMenu popUpContextMenu:menu withEvent:event forView:(NSButton *)sender];
    }
    
    -(IBAction)addFavorite:(id)sender{
        NSLog(@"add");
    }
    
    -(IBAction)manageFavorite:(id)sender{
        NSLog(@"mangage");
    }