NSWindow Troubles

Discussion in 'Mac Programming' started by Blakeasd, Apr 30, 2011.

  1. macrumors 6502a

    Joined:
    Dec 29, 2009
    #1
    Hello,
    I am having some NSWindow troubles... I have an NSWindow following my cursor like this:
    Code:
    - (void)mouseMoved:(NSEvent *)event
    {
        NSPoint p = [NSEvent mouseLocation];
        NSLog(@"%s (%.1f, %1.f)", __PRETTY_FUNCTION__, p.x, p.y);
        
        NSRect f = [self frame];
        if (!NSPointInRect(p, f)) {
            p.x -= f.size.width / 2.0;
            p.y -= f.size.height / 2.0;
            [self setFrameOrigin:p];
            NSLog(@"%s Moved window to (%.1f, %1.f)", __PRETTY_FUNCTION__, p.x, p.y);
        }
        
        [super mouseMoved:event];
    }
    
    The problem is when I click outside of my window (ex. the desktop) my NSWindow subclass stops following my cursor. Is there some way to keep my window in focus even when I click outside of my application?
     
  2. macrumors 65816

    jiminaus

    Joined:
    Dec 16, 2010
    Location:
    Sydney
    #2
    So you want it that once your application get focus, focus never leave your applications?! Sounds like one of those pesky banner popup ads to me that used to plague the Internet before popup blockers.
     
  3. thread starter macrumors 6502a

    Joined:
    Dec 29, 2009
    #3
    I want the Window to following the mouse and when the user clicks the window keeps following. It's not an ad or something bad by the way :)
     
  4. macrumors 65816

    jiminaus

    Joined:
    Dec 16, 2010
    Location:
    Sydney
    #4
    You'll need to create a mouse move event tap using the Quartz Event Services. See this thread for how to set one up.

    Set up the tap in your window delegate's awakeFromNib and tear down the tap in your window delegate's windowWillClose:.

    Use the following code for the eventsOfInterest parameter of CGEventTapCreate.
    Code:
    CGEventMaskBit(kCGMouseEventDeltaX) | CGEventMaskBit(kCGMouseEventDeltaY)
    
    Pass a pointer to your window as the refcon paramter.

    Then code the callback function like this:
    Code:
    CGEventRef eventTapFunction(CGEventTapProxy aProxy, CGEventType aType, CGEventRef anEvent, void *aContext)
    {
        NSEvent *eventWrapper = [NSEvent eventWithCGEvent:anEvent];
        NSWindow *wnd = aContext;
        [wnd mouseMoved:eventWrapper];
        return anEvent;
    }
    
    One issue I can think of is that if your application is the active application, your window will be two mouseMoved: messages, one from your event tap function, and then a second one from the normal Cocoa event handling mechanism.

    If this is an issue, use your application delegate's applicationDidBecomeActive: and applicationDidResignActive: to track your application's active status. If your application is active, don't call mouseMoved: in your event tap function.
     

Share This Page