If you don't mind using a plugin (and giving it permission to pretty much see everything you do) you could try TouchTask plugin's "Screen update" trigger, i believe this can write the foreground app name/package to a variable and you can then have it do whatever you want with that information.