Programmatically catch app opening / closing Is it possible, via an AppleScript, a background service or daemon, or any other programmatic way, to catch the following events:


a specific app (eg Aperture, Excel ...) being launched,
an app being closed or quitting,
an app going to the foreground or background ?


Purpose would to be change some system state/pref  (eg keyboard layout, screen profile etc) in an app-dependent manner. 

Of course, suggestions of existing solutions are welcome.
You can obtain notifications of applications being launched and quit. Apple's TN2050: Observing Process Lifetimes Without Polling provides the detail.

The best method for general purpose tracking is with NSWorkspace and its NSWorkspaceDidLaunchApplicationNotification and NSWorkspaceDidTerminateApplicationNotification notifications.

I do not believe there is a trivial means to implement these TN2050's methods in AppleScript. You will likely need to write a small Objective-C/Cocoa application or use a third party tool.