Tracking the position of the mouse does seem like a trivial task. At a first glance it seemed like it would be a matter to override the -mouseMoved: selector in my NSView subclass and make sure the window accepts mouseMoved events by calling [[self window] setAcceptsMouseMovedEvents:YES]; when the view had loaded. Well, not exactly. I tried every conceivable combination of placements of these peices of code, including making the view the first responder, but I could never manage to intercept the mouseMoved event.
Then I found out about NSTrackingArea. Perhaps I was being overly ignorant, but from reading the event handling docs, it was not clear to me that I would need to use a tracking area to be able to recieve mouseMoved events.
Using NSTrackingArea is pretty straight forward, although at first I got a cryptic error message in the console:
trackingArea options 0x2 do not specify when the tracking area is active
As it turns out, NSTrackingArea requires a combination of several options to work properly. In this case I needed to supply “NSTrackingMouseMoved+NSTrackingActiveInKeyWindow” in the options: attribute.
Putting the following code in the -viewDidMoveToWindow method in my NSView subclass finally managed to get the view to recieve mouseMoved events:
NSTrackingArea *trackingArea = [[NSTrackingArea alloc] initWithRect:[self frame] options:NSTrackingMouseMoved+NSTrackingActiveInKeyWindow owner:self userInfo:nil]; [self addTrackingArea:trackingArea]; [self becomeFirstResponder];
