I want to be notified when the current application will change. I looked at NSWorkspace. It will send notifications only when your own application becomes active or loses the activity. I want to be informed about every application. How can I do this in Cocoa?
2 Answers
If you're targeting 10.6 or later there's a notification for this:
// NSWorkspaceDidActivateApplicationNotification [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(foremostAppActivated:) name:NSWorkspaceDidActivateApplicationNotification object:nil]; 2 Comments
Jimmie Tyrrell
Confirmed working in 2014 on OS X 10.9 (except I had to remove the colon in the @selector method). Thank you!
mrwalker
The colon is there because I expect your selector to look like this:
- (void)foremostAppActivated:(NSNotification *)notificationThank you Jason. kEventAppFrontSwitched in Carbon Event Manager is the magic word
- (void) setupAppFrontSwitchedHandler { EventTypeSpec spec = { kEventClassApplication, kEventAppFrontSwitched }; OSStatus err = InstallApplicationEventHandler(NewEventHandlerUPP(AppFrontSwitchedHandler), 1, &spec, (void*)self, NULL); if (err) NSLog(@"Could not install event handler"); } - (void) appFrontSwitched { NSLog(@"%@", [[NSWorkspace sharedWorkspace] activeApplication]); } And the handler
static OSStatus AppFrontSwitchedHandler(EventHandlerCallRef inHandlerCallRef, EventRef inEvent, void *inUserData) { [(id)inUserData appFrontSwitched]; return 0; } 2 Comments
Jason Coco
Yeah, I made a little example for somebody that actually posted notifications a while back, but I couldn't find it. You gave a nice summary, you should accept this answer :)
Christoph
Remark: To successfully build an application using this, you have to add the Carbon and Core Services Frameworks to your build and include <Carbon/Carbon.h> and <CoreServices/CoreServices.h> in the implementation file that contains the handler. See stackoverflow.com/questions/801976/… on how to mix C with Objective-C