将应用程序设置为applescript中的最前面

问题描述 投票:0回答:3

我试图找出最前面的应用程序 x 是什么,运行一个脚本,然后使用 applescript 将 x 设置为最前面的应用程序。

    tell application "System Events"
set frontApp to displayed name of first process whose frontmost is true
set apptemp to frontApp
end tell

[代码在这里]

tell application "System Events"
set frontmost of process whose name is apptemp to true
end tell

虽然此代码不会返回任何错误,但它不起作用。我也试过这个代码

tell application "System Events"
set apptemp to application "Google Chrome"
set frontmost of process "Google Chrome" to true
end tell

但是,虽然没有错误,但它不会工作。

另外,请告诉管理员以便更容易显示代码。我在这个网站上显示代码最困难。我必须为每行代码缩进四个空格,这太疯狂了。

applescript
3个回答
6
投票

处理此问题的一个可靠方法是使用

path to frontmost application
,如下所示:

# Save which application is frontmost (active),
# as an absolute, HFS-style path string pointing to the application bundle.
set frontmostAppPath to (path to frontmost application) as text

# Activate and work with another application.
activate application "Reminders"
delay 2

# Make the previously frontmost (active) application frontmost again.
activate application frontmostAppPath

使用应用程序的特定路径可确保重新激活完全相同的应用程序,无论是否存在重复项以及 process 名称不同的应用程序。

注意:很想保存和恢复对象引用

frontmost application
直接,但这实际上不起作用:令人费解的是,这样保存的引用被视为与current应用程序(运行代码)。


3
投票

比其他两种方法更好的是使用捆绑标识符,它是唯一的密钥。

tell application "System Events"
    set frontAppID to bundle identifier of first process whose frontmost is true
end tell

-- Sample code... can be anything else
activate application "Finder"
delay 3
-- End of sample code

activate application id frontAppID

0
投票

当多个实例运行时,捆绑包和路径会失败。请使用

unix id
,例如 https://StackOverflow.com/a/78130117/3008405

© www.soinside.com 2019 - 2024. All rights reserved.