views:

657

answers:

4

I'd like to get the list of running applications in the same order they appear when doing ⌘ + ⇥

I.e. if I use TextEdit, then Preview, then iCal, the order is

  1. iCal
  2. Preview
  3. TextEdit

Using [[NSWorkspace sharedWorkspace] launchedApplications] does not work as applications are sorted by launch date/process id. Enumerating with GetNextProcess does not work either as it is also ordered by pid.

Registering for notifications and maintaining a list myself is not an option as I must know the list right after the application launches. Well, the first element of the list would be enough actually, but I think it is pretty much the same question.

Is there some API available to get this information?

+2  A: 

You need to register for notifications when the active application changes, as outlined here: http://www.unsanity.org/archives/000045.php

Once that is done it is easy to maintain an array of active applications sorted by last active time.

sbooth
+2  A: 

It is impossible to get the list before your application launches. After you start the application though, you can just register for notifications and maintain your own array of applications.

The only solution is to start a background process at login using launchd that simply listens for applications.

+2  A: 

Maybe this one:

$ cd /System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework

$ nm LaunchServices | grep __LSCopyApplicationArrayInFrontToBackOrder

nst
Great, it works exactly as expected. It's a pity that it does not come as a documented LaunchServices API.
0xced
And here is how to use _LSCopyApplicationArrayInFrontToBackOrder safely: http://gist.github.com/163918
0xced
+1  A: 

Try enumerating the list of windows with the Accessibility or CGWindowList APIs. Apps aren't windows on Mac OS X, as I'm sure you know, but the front-to-back order of applications should be determined by the front-to-back order of their frontmost windows.

You will, of course, need to ignore processes you've already seen windows from (that is, only consider their frontmost windows).

Peter Hosey
Unfortunately, this solution will not work because as you said, apps aren't window and an app without any window can't be found with this method. Also, the front to back order may be right if you only have one space, but does not work with multiple spaces.
0xced