Setting variable with frontmost app name

How can I tell AppleScript to find out what the frontmost application is, and then set it to a variable (frontmostApp)?

set frontApp to path to frontmost application

This returns an alias. To get its name, use:

tell application “Finder” to set frontAppName to displayed name of frontApp

OK, but when I type that in, it says it can’t get its name. What I want to do is use it in an application that adds accents in text without all of the key combinations. So, it would be using system events as well.


tell frontApp
	activate
end tell

tell application "System Events"
	get properties
	tell process frontApp
		set frontmost to true
	end tell

keystroke "e" with option down
	delay 1
	keystroke "e"
	keystroke return
end 

‘frontApp’ is not a reference to the application, it’s the application name, so ‘tell frontApp’ won’t work. You need to use:

tell application frontApp

I can’t recall if System Events uses the actual name of the app rather than the displayed name. Unfortunately I can’t check here at work (no OSX). If no one can help before tonight, I’ll test your algorithm and see what I can help with.

To get the name of the frontmost process, this should work:

tell application "System Events" to set fm to name of first process whose frontmost is true

Then, to use it later, this should work:

tell application "System Events"
	try
		set frontmost of process fm to true
	on error err
		display dialog err
		return
	end try
	keystroke "e" with option down
	delay 1
	keystroke "e"
	keystroke return
end tell

– Rob

OK, thanks. I’ve got the code set. Now, how can I make the window “float” above all of the rest. When I press a button, it says that the variable is not defined (which it is). Also, it dosen’t type because it is the frontmost application. Can someone help me here?

I don’t know which window or button you are referring to so it’s hard to say what the problem might be.

– Rob

The window (which is called “main”) has several buttons on it, which are supposed to put a piece of text into the word processor when a button is pressed.

So I assume that you are building an AppleScript Studio app. I don’t use Studio so I don’t know what it offers along these lines. Maybe you can momentarily send your app to the back while the commands are sent to the target app.

tell application "System Events"
	set frontmost of process "your app" to false
	keystroke "e" with option down
	delay 1
	keystroke "e"
	keystroke return
	set frontmost of process "your app" to true
end tell

Seems like a kludge but maybe it is a satisfactory kludge if nothing else is available.

– Rob