Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting notified when the current application changes in Cocoa

Tags:

cocoa

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?

like image 322
cocoafan Avatar asked Apr 18 '09 06:04

cocoafan


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];

Apple docs: http://developer.apple.com/library/mac/DOCUMENTATION/Cocoa/Reference/ApplicationKit/Classes/NSWorkspace_Class/Reference/Reference.html#//apple_ref/doc/uid/20000391-SW97

like image 126
mrwalker Avatar answered Oct 01 '22 13:10

mrwalker


Thank 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;
}
like image 37
cocoafan Avatar answered Oct 01 '22 15:10

cocoafan