Min Joo
Min Joo

Reputation: 23

How can I detect what application is running on OSX

I want to make my application as menu bar app and I made it already. And also I want to track what application is running.

NSRunningApplication method returns all runnng applications. But I want to detect the only application that is activated now. (with mouse click or command + tab...) How can I find that?

I made code below :

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
     [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(performTimerBasedUpdate) userInfo:nil repeats:YES];
}

- (void)performTimerBasedUpdate {
     nowRunning = [NSRunningApplication currentApplication];
     nowRunningName = [nowRunning localizedName];
}

But, It returns the application name that I made (self).

I finally find the answer : thank you i-blis. I can get the activated application with filter. I didn't know about isActive property!

runningApplications_ = [[NSWorkspace sharedWorkspace] runningApplications];
nowRunning = [[runningApplications_ filteredArrayUsingPredicate:isActive] objectAtIndex:0];
bundleIdentifier_ = [nowRunning bundleIdentifier];
localizedName = [nowRunning localizedName];

Upvotes: 2

Views: 3796

Answers (2)

self
self

Reputation: 1215

NSWorkspace *workSpace = [NSWorkspace sharedWorkspace];

NSString *appPathIs = [workSpace fullPathForApplication:appName];

NSString *identifier = 
   [[NSBundle bundleWithPath:appPathIs] bundleIdentifier];

NSArray *selectedApps = 
   [NSRunningApplication runningApplicationsWithBundleIdentifier:identifier];

Upvotes: 2

i-blis
i-blis

Reputation: 3179

You can easily find if an application is active with isActive. Then peek the localizedName or bundleIdentifier at your will. I am not really fluent in Objective-C but with Macruby syntax you'll get it in the following way :

NSWorkspace.sharedWorkspace.runningApplications
    .select { |e| e.isActive == true }
    .map { |e| e.localizedName }

You may need to filter out your own application: I did not test how menu bar apps are handled in this regard.

Upvotes: 5

Related Questions