Applescript detecting file or app open/close?


Can an applescript detect file open/close or application start/shutdown

Can an applescript sit in the background and open another
application whenever it detects that a file has been opened
or closed, or an application (other than the one this script
opens) has been started or quit from?

If so, can someone point me to the appropriate section of the



Crotchety UI Nitpicker
I don't know of any good way to detect when a file is opened, but you can check which apps are loaded farily easily with an invisible process called System Events. Here's a quick example that will respond every time Safari is launched or quit, by periodically checking whether it is currently loaded:
global wasLoaded

on run
	set wasLoaded to isAppLoaded("Safari")
end run

on idle
	set x to isAppLoaded("Safari")
	if x and not wasLoaded then
		display dialog "Safari was loaded."
		set wasLoaded to true
	else if wasLoaded and not x then
		display dialog "Safari was quit."
		set wasLoaded to false
	end if
	return 1 --will wait 1 second before checking again
end idle

on isAppLoaded(app_name)
	tell application "System Events"
		set app_list to every application process whose name contains app_name
		if the (count of app_list) > 0 then
			return true
			return false
		end if
	end tell
end isAppLoaded
Note that this will only work when the script is launched as an application saved with the "Stay Open" box checked, because the idle event will not be repeatedly called otherwise. You could also rework this to avoid using the idle event by putting the code from my idle handler into a loop and calling "delay 1" at the end of the loop. (But then you'd need to implement your own way to quit it.)

System Events is located at "/System/Library/CoreServices/System". You may want to check out its scripting dictionary.


Sample code:

on idle {}
	my handleProcesses()
	return 10 -- The '10' tells 'idle ()' to execute every 10 seconds.
end idle

on handleProcesses()
	tell application "Finder" to set tProcesses to name of processes
	if (tProcesses contains "Eudora") then
		say "Eudora is currently launched"
		say "Eudora is not currently launched"
	end if
end handleProcesses
Save as an 'application' and the 'Options:' 'Stay Open' check box check marked.


Thanks folks. I'll have a bash at it when I get some spare time.

I've not written any applescript before, but I'm trying to solve a time tracking problem without spending too much money. I figure if I can get a text file to open up every time I close one of several apps, I can at least write a quick note about what I was working on at the time.