PDA

View Full Version : Make NSWindow Follow Mouse Cursor




Blakeasd
Apr 2, 2011, 09:39 PM
Hello,
How can I make an NSWindow follow my mouse cursor in Objective-C and Cocoa.
Thanks



jiminaus
Apr 3, 2011, 12:06 AM
Subclass NSWindow with the following:


- (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
Apr 3, 2011, 08:31 AM
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.