aktivb
aktivb

Reputation: 2082

Set focus to specific window of an application using applescript

How can I set focus to a specific window of a given application using applescript?

I have several iTerm2 windows running on different displays. I want to set focus to a specified window using applescript.

I need two things, one script that collects the window ID's and prints them to stdout. I've got this:

tell application "iTerm"
  set wins to id of every window
end tell

which prints 6 integers: 3034, 2528, -1, -1, -1, -1

Bonus Question: What are the four -1's ?

Then I try:

tell application "System Events"
  activate window 3034
end tell

Upon which the only thing happening is that I lose focus of my current terminal (in which I am typing these commands), not matter whether I specify 3034 or 2528 as the ID.

Upvotes: 8

Views: 15018

Answers (1)

Digital Trauma
Digital Trauma

Reputation: 16016

You almost have it. You can filter out the "-1" window IDs as by only looking at visible windows:

tell application "iTerm 2"
  set wins to id of every window whose visible is true
end tell

I figured this out by looking at the results of:

tell application "iTerm 2" to properties of every window

I noticed that the "-1" windows have the property visible:false

Then you can tell the window ID directly to the iTerm application instead of system events:

tell application "iTerm 2"
  activate window 13195
end tell

Upvotes: 2

Related Questions