2012-03-08 89 views
0

如果沒有終端應用程序打開,則以下代碼將打開兩個終端窗口。它爲什麼這樣做?我只想要打開一個窗口。爲什麼2個終端窗口用NSAppleScript打開?

如果只有一個終端窗口打開,則以下代碼僅打開一個附加窗口。

NSAppleScript* terminal = [[NSAppleScript alloc] initWithSource: 
          [NSString stringWithFormat: 
           @"tell application \"Terminal\"\n" 
           @" activate\n" 
           @" do script \"echo %@\"\n" 
           @" tell the front window\n" 
           @" set title displays shell path to false\n" 
           @" set title displays custom title to true\n" 
           @" set custom title to \"My session! %@\"\n" 
           @" end tell\n" 
           @"end tell", name, name]]; 

[terminal executeAndReturnError:nil]; 
+0

當你說兩終端「應用」,你的意思是兩個終端窗口或應用程序的兩個實例實際? – zmccord 2012-03-08 03:27:43

+0

兩個窗口 - 感謝撿起 – Coderama 2012-03-08 03:30:27

回答

1

如您所寫,do script命令將始終運行在新窗口中。如果您希望它在特定窗口中運行,請使用以下格式:do script (...) in (window...)。終端的in語法也可以處理標籤中的運行腳本。

例如,如果您想在最前面的窗口中運行腳本,您可以編寫do script "echo Hello, world!" in front window


編輯:跟進,如果你想一直在窗口中運行該腳本(創建一個新的,如果沒有打開),你可以使用下面的AppleScript:

tell application "Terminal" 
    activate 
    if length of (get every window) is 0 then 
     tell application "System Events" to tell process "Terminal" to click menu item "New Window" of menu "File" of menu bar 1 
    end if 
    do script "echo Hello, world!" in front window 
end tell 

當然,您需要在NSArray中正確轉義它,但我相信您可以做到。

+0

我確實希望我的'echo'命令始終在新窗口中運行。問題是當沒有窗戶打開時,我的腳本將打開兩個窗口而不是一個窗口。 – Coderama 2012-03-08 04:06:07

+0

@Coderama看我的編輯。 – 2012-03-08 04:09:43

+0

不錯的工作!我以另一種方式去了解它,並做了一個'如果它正在運行' – Coderama 2012-03-08 04:47:37

0

這裏是我的解決方案以進行比較:

tell application "Terminal" 
    if it is running then 
     do script "echo %@" 
    else 
     activate 
     do script "echo %@" in front window 
    end if 
    tell the front window 
     set title displays shell path to false 
     set title displays custom title to true 
     set custom title to "My Terminal!" 
    end tell 
end tell 
+0

我剛剛意識到我的解決方案不起作用,如果終端運行沒有任何窗口打開 – Coderama 2012-03-08 05:11:18

+1

是的。 'activate'將確保它正在運行,並且在前臺(替換'如果正在運行'),其餘的將確保至少有一個窗口可以工作。 – 2012-03-08 13:16:51

相關問題