DrummerB
DrummerB

Reputation: 40211

Observe global mouse location on screen in Cocoa?

I'd like to be notified when the mouse moves and get the location on the screen. I tried this:

[NSEvent addGlobalMonitorForEventsMatchingMask:NSMouseMovedMask handler:^(NSEvent *event) {
    CGPoint location = [NSEvent mouseLocation];
    NSLog(@"Position: %@", NSStringFromPoint(location));
}];

However this seems to only work as long as the mouse is in my app's window. As soon as leave it I'm not notified. Until I enter the window again. Shouldn't this event be global?

UPDATE:

I extracted the code in question and made a separate sample project (Dropbox-Link). Just to be sure, there is nothing else interfering with it. It's a clean project with just the code above in applicationDidFinishLaunching:. I get the same results and it's really strange. I uploaded a video to youtube: http://www.youtube.com/watch?v=I3AKgmURaMk.

These are my observations:

  1. Immediately after launching the app, no events at all are delivered, no matter where I move the mouse.
  2. Clicking the app's window will somehow activate event delivery. Now I receive NSMouseMovedMask events, no matter where I move the mouse (this is what I want to achieve).
  3. Clicking back to Xcode doesn't change anything. I keep getting the events.
  4. However, moving the focus back to my app results in a strange behavior. When I move my mouse over Xcode I only get events over some parts of the window, while some parts seem to absorb the event. More specifically I don't receive events over the editor or the log view. I only receive them while moving the mouse over the gray split view separator area (with the tab bars embedded in them).

Upvotes: 4

Views: 1910

Answers (1)

Andrew
Andrew

Reputation: 41

It should work, I've seen weird behavior when the window is up but not in the foreground. I've noticed that if the application is in the background but not in the dock you will only get events when the mouse transitions between windows in the foreground. Minimizing the application seems to fix this problem.. I'm very new at cocoa dev/ObjC.. I might be wrong, but I've noticed when I minimize my app, I get all events.

Upvotes: 1

Related Questions