Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

Blakeasd

macrumors 6502a
Original poster
Dec 29, 2009
643
0
Hello,
How can I make an NSWindow follow my mouse cursor in Objective-C and Cocoa.
Thanks
 

jiminaus

macrumors 65816
Dec 16, 2010
1,449
1
Sydney
Subclass NSWindow with the following:

Code:
- (id)initWithContentRect:(NSRect)contentRect
                styleMask:(NSUInteger)windowStyle
                  backing:(NSBackingStoreType)bufferingType
                    defer:(BOOL)deferCreation
{
    NSLog(@"%s", __PRETTY_FUNCTION__);
    self = [super initWithContentRect:contentRect styleMask:windowStyle backing:bufferingType defer:deferCreation];
    if (self) {
        [self setAcceptsMouseMovedEvents:YES];
    }
    return self;
}


- (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];
}

You can probably do the same thing with a window delegate as well.

You might want to tweak exactly how you move the window and add logic to keep the window fully on screen.
 

Blakeasd

macrumors 6502a
Original poster
Dec 29, 2009
643
0
How exactly would I tweak the windows location relevant to the mouse? Also how can I keep the window moving when the mouse clicks on something other than the window. Thanks for everything so far, you've been extremely helpful.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.