gpt4 book ai didi

applescript - 使用应用程序作为变量激活 Applescript 中的应用程序

转载 作者:行者123 更新时间:2023-12-05 01:18:15 27 4
gpt4 key购买 nike

我正在尝试编写一个脚本来记录当前应用程序、切换到另一个应用程序、执行一些任务并返回到原始应用程序。这就是我所拥有的

set currentApp to my getCurrentApp()
activate application "Safari"
# Some task
activate application currentApp

to getCurrentApp()
set front_app to (path to frontmost application as Unicode text)
set AppleScript's text item delimiters to ":"
set front_app to front_app's text items
set AppleScript's text item delimiters to {""} --> restore delimiters to default value
set item_num to (count of front_app) - 1
set app_name to item item_num of front_app
set AppleScript's text item delimiters to "."
set app_name to app_name's text items
set AppleScript's text item delimiters to {""} --> restore delimiters to default value
set MyApp to item 1 of app_name
return MyApp
end getCurrentApp

奇怪的是,如果您输入字符串文字,激活应用程序命令会起作用,但是如果您传递给它一个字符串变量,它不会激活应用程序。任何想法为什么?

最佳答案

你的脚本对我有用。使用字符串变量激活应用程序在任何版本的 OSX 中总是有效的......所以你会遇到一些不同的问题。问题不在于您显示的代码。

尽管您的代码有效,但您可以像这样缩短 getCurrentApp() 子例程...

set currentApp to my getCurrentApp()
activate application "Safari"
delay 1
activate application currentApp

to getCurrentApp()
return (path to frontmost application as text)
end getCurrentApp

如果您还从激活行中删除“应用程序”,您甚至不需要在子例程中使用“作为文本”...
set currentApp to my getCurrentApp()
activate application "Safari"
delay 1
activate currentApp

to getCurrentApp()
return (path to frontmost application)
end getCurrentApp

所以毕竟说了又做了,你的代码可能看起来像这样......
set currentApp to path to frontmost application
activate application "Safari"
delay 1
activate currentApp

编辑 : 有时当你试图获取最前面的应用程序时,你正在运行的applescript 是最前面的应用程序,而不是你认为最前面的应用程序。很难检测到这种情况何时发生,但我怀疑这可能发生在您身上。所以这是我使用获取最前面应用程序的子例程。这可确保 Applescript 不会作为最前面的应用程序返回。尝试一下,看看它是否有帮助...
on getFrontAppPath()
set frontAppPath to (path to frontmost application) as text
set myPath to (path to me) as text

if frontAppPath is myPath then
try
tell application "Finder" to set bundleID to id of file myPath
tell application "System Events" to set visible of (first process whose bundle identifier is bundleID) to false

-- we need to delay because it takes time for the process to hide
-- I noticed this when running the code as an application from the applescript menu bar item
set inTime to current date
repeat
set frontAppPath to (path to frontmost application) as text
if frontAppPath is not myPath then exit repeat
if (current date) - inTime is greater than 2 then exit repeat
end repeat
end try
end if
return frontAppPath
end getFrontAppPath

关于applescript - 使用应用程序作为变量激活 Applescript 中的应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13097426/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com