16

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?

0xced
  • 25,219
  • 10
  • 103
  • 255

4 Answers4

19

Maybe something like this:

cd /System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework
nm LaunchServices | grep __LSCopyApplicationArrayInFrontToBackOrder
alexwlchan
  • 5,699
  • 7
  • 38
  • 49
nst
  • 3,862
  • 1
  • 31
  • 40
  • Great, it works exactly as expected. It's a pity that it does not come as a documented LaunchServices API. – 0xced Aug 06 '09 at 19:30
  • 9
    And here is how to use _LSCopyApplicationArrayInFrontToBackOrder safely: http://gist.github.com/163918 – 0xced Aug 07 '09 at 14:10
  • Hey @0xced I am kinda noob how to execute that file. So far I've added that in my Xcode but how to call that. – user4150758 Jul 28 '22 at 19:22
3

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.

0xced
  • 25,219
  • 10
  • 103
  • 255
sbooth
  • 16,646
  • 2
  • 55
  • 81
3

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.

1

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
  • 95,783
  • 15
  • 211
  • 370
  • 1
    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 Aug 06 '09 at 16:58