Can ASObjC be used to set the openApps and activeApp variables in the following:
tell application "System Events"
set openApps to name of every process whose background only is false
set activeApp to name of first process whose frontmost is true
end tell
Right now I use the following, but I believe this returns app names rather than process names:
set openApps to current application's NSWorkspace's sharedWorkspace()'s runningApplications()
set thePredicate to current application's NSPredicate's predicateWithFormat:"activationPolicy = 0"
set openApps to openApps's filteredArrayUsingPredicate:thePredicate
set activeApp to current application's NSWorkspace's sharedWorkspace()'s frontmostApplication()
This is used with a script which contains code such as the following:
tell application "System Events"
tell process (localizedName of item (i - 1) of openApps as text)
set frontmost to true
end tell
end tell
The reason I would prefer not to use System Events to set openApps and activeApp is that it’s relatively slow in my testing. Thanks for the help.
Can you use process identifiers instead?
set activeApp to current application's NSWorkspace's sharedWorkspace()'s frontmostApplication()'s processIdentifier()
tell application "Finder" to activate
delay 1
tell application "System Events"
tell (process 1 whose unix id is activeApp)
set frontmost to true
end tell
end tell
Thanks Shane–that works great.
I plugged the revised code into my script and it works as expected. I ran some timing tests and the revised script is only marginally slower than my script which used app names with processes but still significantly faster than using System Events to get process names.
FWIW, the revised code segment:
set openApps to current application's NSWorkspace's sharedWorkspace()'s runningApplications()
set thePredicate to current application's NSPredicate's predicateWithFormat:"activationPolicy = 0"
set openApps to (openApps's filteredArrayUsingPredicate:thePredicate)'s valueForKey:"processIdentifier"
set activeApp to current application's NSWorkspace's sharedWorkspace()'s frontmostApplication()'s processIdentifier()
set i to ((openApps's indexOfObject:activeApp) + 1)
if i > 2 then
tell application "System Events"
tell (process 1 whose unix id is (item (i - 1) of openApps) as integer)
set frontmost to true
end tell
end tell
end if