为什么2个终端窗口用NSAppleScript打开?
如果没有终端应用程序打开,则以下代码将打开两个终端窗口。它为什么这样做?我只想要打开一个窗口。为什么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];
如您所写,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
中正确转义它,但我相信您可以做到。
这里是我的解决方案以进行比较:
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
我刚刚意识到我的解决方案不起作用,如果终端运行没有任何窗口打开 – Coderama 2012-03-08 05:11:18
是的。 'activate'将确保它正在运行,并且在前台(替换'如果正在运行'),其余的将确保至少有一个窗口可以工作。 – 2012-03-08 13:16:51
当你说两终端“应用”,你的意思是两个终端窗口或应用程序的两个实例实际? – zmccord 2012-03-08 03:27:43
两个窗口 - 感谢捡起 – Coderama 2012-03-08 03:30:27