为什么2个终端窗口打开NSAppleScript?

时间:2012-03-08 03:22:43

标签: objective-c cocoa

如果没有打开终端应用程序,则以下代码将打开两个终端窗口。它为什么这样做?我只想打开一个窗口。

如果只打开了一个终端窗口,则以下代码仅打开一个附加窗口。

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];

2 个答案:

答案 0 :(得分: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中正确地逃避它,但我相信你能做到。

答案 1 :(得分: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