How to verify if a window/application is (not) in the background

Hi everybody,
I am a big newbie, and I am creating my first little AppleScript script, a very basic script. I manage to do most of it, but there one thing I can’t manage to do, but first let me post my code:


tell application "System Events" to set isRunning to exists process "Terminal"

if isRunning then
	tell application "Finder"
		if visible of process "Terminal" is false then
			set visible of process "Terminal" to true
			tell application "Terminal" to activate
		else
	----->>	if visible of (window 1 of process "Terminal") is false then[/color]
				tell application "Terminal" to activate
			
			else           <<-----
				set visible of process "Terminal" to false
	----->>	end if         <<-----
		end if
	end tell
else
	tell application "Terminal" to activate
end if

Basically the code that is between the arrows does not work, and it’s the part I can’t make work obviously. Basically what the script does (or/and is supposed to do) is:
-Check if the Terminal is open.
–if it’s open check if it’s visible
—if it’s visible, hide it
—if it’s invisible show it
–if it’s not open open it.

The proble I have is the following:
If for instance the Terminal is open and I click on another app that is in the background, the terminal will still be visible. So if I want to bring it back I have to run the script twice. That’s why I want to check if it’s in the background or not. If it’s in the background I want to show it, else I hide it.

I tried to use: if process “Terminal” is running in the back, but I got this error: Finder got an error: Can’t get last insertion point.
Can somebody help me with this please?

Thanks in advance,
Aziz

Hi Aziz,

try this, it’s recommended to prefer System Events to control the processes


tell application "System Events" to set isRunning to exists process "Terminal"

if isRunning then
	tell application "System Events" to tell process "Terminal" to set visible to not (get visible) -- toggles the visible status
else
	activate application "Terminal"
end if

in the back is no AppleScript terminology at all :wink: