Reputation: 1574
I have an application that is using Apple's NSTrackingArea API to handle mouseEntered
, mouseMoved
and mouseExited
events by calling NSView::addTrackingArea
. This generally works well, except I would like to be able to track the location of the cursor on the screen during drag events.
Is there a way to subscribe to an NSView's events to determine the location of the cursor during mouse drag events?
My current code snippet:
- (instancetype)initWithCallback:(LocationUpdateCallback)callback
andView:(NSView*)nsView {
if ((self = [super init])) {
_callback = std::move(callback);
constexpr NSTrackingAreaOptions kTrackingOptions =
NSTrackingMouseMoved | NSTrackingMouseEnteredAndExited |
NSTrackingActiveInKeyWindow | NSTrackingInVisibleRect |
NSTrackingEnabledDuringMouseDrag;
NSTrackingArea* trackingArea =
[[NSTrackingArea alloc] initWithRect:NSZeroRect
options:kTrackingOptions
owner:self
userInfo:nil];
_trackingArea.reset(trackingArea);
[nsView addTrackingArea:trackingArea];
}
return self;
}
- (void)mouseMoved:(NSEvent*)theEvent {
...
}
- (void)mouseEntered:(NSEvent*)theEvent {
...
}
- (void)mouseExited:(NSEvent*)theEvent {
...
}
Upvotes: 1
Views: 101
Reputation: 1574
I came to the conclusion that the NSTrackingArea API just doesn't support finding the mouse location, and used Willeke's suggestion to use an event monitor for drag events. Adding the below code snippet produces the behavior I desired:
NSEvent* (^mouseDragged)(NSEvent*) = ^NSEvent*(NSEvent* event) {
// Handle the mouse dragged event.
...
return event;
};
const NSEventMask drag_mask = NSEventMaskLeftMouseDragged |
NSEventMaskRightMouseDragged |
NSEventMaskOtherMouseDragged;
_monitor_id = [NSEvent addLocalMonitorForEventsMatchingMask:drag_mask
handler:mouseDragged];
Upvotes: 0