问题
I have a simple snippet(not MVC) of code looking like the following
# include <Cocoa/cocoa.h>
int main(argc, *argv[]) {
[NSApplication sharedApplication]
[NSEvent addGlobalMonitorForEventsMatchingMask:NSKeyUpMask handler:^(NSEvent *evt){ .... }]
[NSApp run]
}
When compiled as command line binary and run, the global event monitoring works, after allowing the program from system preferences -> privacy & security; then I packed it int an .app, and ran it, the global monitor stopped working even after allowing the app from privacy & security.
I'm new to Cocoa, in order to implement a simple global monitor for a packaged app, what do I need to do else?
回答1:
then I packed it int an .app
Did you put your CLI program in an app bundle or did you start over with a new graphical Cocoa Application?
I'd suggest you create a new GUI app using Xcode's project window and then use the following snippet as your applicationDidFinishLaunching: implementation:
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
Boolean isTrusted = AXIsProcessTrustedWithOptions(CFDictionaryCreate(NULL, (const void*[]){ kAXTrustedCheckOptionPrompt }, (const void*[]){ kCFBooleanTrue }, 1, NULL, NULL));
if(isTrusted)
{
[NSEvent addGlobalMonitorForEventsMatchingMask:NSKeyUpMask handler:^(NSEvent *evt){ NSLog(@"Received NSKeyUp event."); }];
}
}
This will automatically bring up the System Preference pane that allows the user choose wether your application should be trusted. AXIsProcessTrustedWithOptions requires OS X 10.9 (Mavericks).
Update
There are some pitfalls regarding "Support for assistive devices" when debugging a global event monitor:
- When launching the app bundle via Xcode "Build & Run" with an attached debugger, Xcode also needs to be granted Accessibility rights in the Privacy pref pane
- The global event monitor does not receive events when a window from the Cocoa app that installed the monitor is in the foreground.
来源:https://stackoverflow.com/questions/21302593/is-user-interface-required-in-order-to-do-global-event-monitoring-in-cocoa