Search code examples
macoscocoamouseeventnswindowappkit

Event for mouse leaving a NSWindow instance


Is there a mechanism for detecting when the mouse leaves the active NSWindow bounds?

I've already tried overriding the mouseMoved: method, but that is not called when the mouse is outside the NSWindow bounds.


Solution

  • The best is to use NSTrackingArea

    - (void)configureTrackingArea
    {
        NSRect trackingRect = self.window.contentView.frame
        NSTrackingAreaOptions trackingOptions = NSTrackingMouseEnteredAndExited | NSTrackingActiveInKeyWindow;
        NSTrackingArea *trackingArea = [[NSTrackingArea alloc] initWithRect:trackingRect options:trackingOptions owner:self userInfo:nil];
    
        NSView *contentView = [[self window] contentView];
        [contentView addTrackingArea:trackingArea];
    }
    
    
    - (void)mouseEntered:(NSEvent *)event
    {
        [[self window] addChildWindow:[self previewWindow] ordered:NSWindowAbove];
    }
    
    - (void)mouseExited:(NSEvent *)event
    {
        [self hidePreviewWindow];
    }