loyalflow
loyalflow

Reputation: 14879

How to determine when an application becomes active and in-active?

How can you determine when a particular application becomes active and in-active?

Example, the user opens chrome, then switches to textmate, then switches back to chrome.

I want to be able to track when and what the active application is.

Upvotes: 1

Views: 1166

Answers (2)

Daij-Djan
Daij-Djan

Reputation: 50089

In the NSApplicationDelegate you have

Managing Active Status -- for your OWN app only!

  • applicationWillBecomeActive:
  • applicationDidBecomeActive:
  • applicationWillResignActive:
  • applicationDidResignActive:

those are in fact NSNotifications sent by the your own NSApplication object


one notification is for ALL apps!

  • NSWorkspaceDidActivateApplicationNotification

that's sent by the NSWorkspace Object

Upvotes: 6

jscs
jscs

Reputation: 64002

The current active application:

NSRunningApplication * frontmost;
frontmost = [[[NSWorkspace sharedWorkspace] runningApplications] filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"active == YES"]][0];

You can get a notification every time a new application is activated like so:

_myObserver = [[[NSWorkspace sharedWorkspace] notificationCenter] addObserverForName:NSWorkspaceDidActivateApplicationNotification
                                                                object:nil
                                                                 queue:nil
                                                            usingBlock:^(NSNotification *note) {
    NSLog(@"New application: %@", [[note userInfo] objectForKey:NSWorkspaceApplicationKey]);
}];

Upvotes: 4

Related Questions