1. Welcome to the new MacRumors forums. See our announcement and read our FAQ

Make NSWindow Follow Mouse Cursor

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

  1. macrumors 6502a

    How can I make an NSWindow follow my mouse cursor in Objective-C and Cocoa.
  2. macrumors 65816


    Subclass NSWindow with the following:

    - (id)initWithContentRect:(NSRect)contentRect
        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.
  3. macrumors 6502a

    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.

Share This Page