Trigger Script When App Opens?

What’s the best way to trigger a script based on the status of an application?

I’d like to be able do so when an app opens, when it quits, when it’s in front, when it’s not in front… you get the idea.

As usual, I’m over my head and any hints would be most welcome.


Save this as a stay-open application

global procName

global initActivated
global initKilled
global initFront
global initNotFront

on run
	tell application "System Events" to set allProcs to name of every process whose visible is not false
	set procName to (choose from list allProcs with prompt "Choose a process to monitor")
	if procName is false then quit
	set procName to procName as string
end run

on idle
	tell application "System Events"
		set nowActivated to (exists process procName)
		set nowKilled to not (exists process procName)
		set nowFront to frontmost of process procName
		set nowNotFront to not (frontmost of process procName)
	end tell
	if nowActivated is true and initActivated is false then
		-- code to be executed when app launches
	end if
	if nowKilled is true and initKilled is false then
		-- code to be executed when app quits
	end if
	if nowFront is true and initFront is false then
		-- code to be executed when app gets frontmost
	end if
	if nowNotFront is true and initNotFront is false then
		-- code to be executed when app gets in the background
	end if
	set initActivated to nowActivated
	set initKilled to nowKilled
	set initFront to nowFront
	set initNotFront to nowNotFront
	return 1
end idle

on registerFlags(processName)
	tell application "System Events"
		if not (exists process processName) then
			set initActivated to false
			set initKilled to true
			set initFront to false
			set initNotFront to false
			set initActivated to true
			set initKilled to false
			set initFront to frontmost of process processName
			set initNotFront to not (frontmost of process processName)
		end if
	end tell
end registerFlags

Hope it works,

NOTE: Not tested, so there could be a couple mistakes in the script

Hey - I can use that. Thanks much.