View Full Version : NSWindow Troubles

Apr 30, 2011, 03:35 PM
I am having some NSWindow troubles... I have an NSWindow following my cursor like this:

- (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?

Apr 30, 2011, 07:11 PM
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.

Apr 30, 2011, 08:13 PM
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 :)

Apr 30, 2011, 09:05 PM
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.

CGEventMaskBit(kCGMouseEventDeltaX) | CGEventMaskBit(kCGMouseEventDeltaY)

Pass a pointer to your window as the refcon paramter.

Then code the callback function like this:

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.