3

I'm pretty newbie with Obj-C and Cocoa. I'm trying to develop a very simple command line app that on launch wait's for a few global mouse events, and quits when done. I've correctly implemented an NSRunLoop to avoid the cli app finishing right away, but I can't seem to grasp the event listening for mouse events.

I'm using this snippet:

[NSEvent addGlobalMonitorForEventsMatchingMask:NSMouseMovedMask handler:^(NSEvent *mouseEvent) {
    NSLog(@"Mouse moved: %@", NSStringFromPoint([mouseEvent locationInWindow]));
}];

I'm my CLI app it simply doesn't fire anything, though it compiles correctly, while it works just fine if pasted inside a blank Cocoa App, in the applicationDidFinishLaunching method in the appDelegate class.

What I'm I missing? Thanks!

pd: I'm not 100% sure it's a CLI what I need though. I could also be an invisible or headless application, without a window, menu item or anything related what so ever, just a process that runs for a few seconds until the criteria is met.

Ramiro Araujo
  • 465
  • 3
  • 11

1 Answers1

2

I would guess you need a running NSApplication to use NSEvent. You could make a headless, icon-less NSApp, I believe.

Wil Shipley
  • 9,343
  • 35
  • 59
  • 2
    I ended up using Quartz events as described here: http://stackoverflow.com/a/3135508/1098460. A little low level for my taste, but does the work – Ramiro Araujo Feb 20 '14 at 02:42
  • NSEvent is included in AppKit. You could import AppKit and try to do it, but CGEvent should be a lot lighter weight for most cases. Although I'm not sure about the weirdness of a CLI app "Requesting to Control Your Computer" would look like... (unless your tool runs as root, then it does not need to ask.) – uchuugaka Feb 20 '14 at 03:41