I implemented the following custom view derived from NSView:

#import "WarpCursorView.h"

@interface WarpCursorView ()

- (CGPoint)centerOnScreen;

@end

@implementation WarpCursorView

- (void)drawRect:(NSRect)dirtyRect
{
}

- (void)mouseMoved:(NSEvent*)event
{
    NSWindow* window = self.window;
    if([window isKeyWindow]){
        ::NSLog(@"Cursor moved with offset %f,%f", event.deltaX, event.deltaY);
    } 
}

- (BOOL)acceptsFirstResponder
{
    return YES;
}

- (BOOL)becomeFirstResponder
{
    [NSCursor hide];
    
    CGPoint center = [self centerOnScreen];
    
    ::CGWarpMouseCursorPosition(center);
    
    ::CGAssociateMouseAndMouseCursorPosition(false);
    
    [self.window setAcceptsMouseMovedEvents:YES];
    return YES;
}

- (BOOL)resignFirstResponder
{
    ::CGAssociateMouseAndMouseCursorPosition(true);
    [NSCursor unhide];
    return YES;
}

- (CGPoint)centerOnScreen
{
    NSRect bounds = [self bounds];
    NSPoint center = {bounds.size.width * 0.5f, bounds.size.height * 0.5f};
    center = [self convertPoint:center toView:nil];
    center = [[self window] convertBaseToScreen:center];
    
    CGPoint result = {center.x, center.y};
    return result;
}

@end

The goal of this view is to place the mouse cursor in the view so the view will 
receieve all button input from the mouse, and to track the relative motion of 
the mouse as it moves.

I placed this view in the Xib for an application, and built the application. I 
then placed the mouse cursor to the far right of the screen, launched the 
application and began moving the mouse cursor to the left.  The program 
produced the following output:

2010-07-05 08:53:44.274 WarpCursor[12212:a0f] Cursor moved with offset 
-978.000000,-9.000000
2010-07-05 08:53:44.291 WarpCursor[12212:a0f] Cursor moved with offset 
-8.000000,0.000000
2010-07-05 08:53:44.307 WarpCursor[12212:a0f] Cursor moved with offset 
-8.000000,-1.000000
2010-07-05 08:53:44.324 WarpCursor[12212:a0f] Cursor moved with offset 
-11.000000,-1.000000
2010-07-05 08:53:44.341 WarpCursor[12212:a0f] Cursor moved with offset 
-5.000000,0.000000
2010

As can be seen, the first logged output contains a very large offset.  This is 
not desired because the expectation is that the program should start tracking 
the mouse movement after the cursors has been placed inside the view.  What can 
done to eliminate an initial large offset like this which can result if the 
mouse cursor is rather far away from where the view will be located when the 
application launches?

_______________________________________________

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Reply via email to