2

我创建了一个在 Automator 中切换键盘查看器的代码。

on run {input, parameters}
    if application "KeyboardViewer" is running then
        quit application "KeyboardViewer"
    else
        activate application "KeyboardViewer"
    end if
    return input
end run

但是,键盘查看器成为当前正在运行的窗口,我无法立即开始输入(我必须切换回上一个窗口)。是否有我可以添加的特定代码,以便再次突出显示上一个窗口?

4

2 回答 2

6

您可以使用launch而不是activate

tell application "KeyboardViewer"
    if running then
        quit
    else
        launch
    end if
end tell

如果应用程序未打开,launch通常会在其他应用程序上方但最前面的应用程序下方打开一个新窗口。否则,它只会将应用程序保留在后台。在第二种情况下,您可以使用AXRaise提升窗口,但它也使它们看起来像活动窗口。

launch application "Terminal"
tell application "System Events" to tell process "Terminal"
    perform action "AXRaise" of windows
end tell

您还可以将以前的应用程序保存在变量中:

set a to path to frontmost application as text
activate application "Terminal"
activate application a

如果您将焦点转移到后台应用程序,您可以稍后激活最前面的应用程序:

try
    tell application "SystemUIServer"
        display dialog "" default answer ""
    end tell
end try
activate application (path to frontmost application as text)
于 2012-10-07T12:06:51.610 回答
1

在激活应用程序“KeyboardViewer”行之后尝试此操作...

tell application "System Events" to keystroke tab using command down

编辑:因为上面的原始帖子没有为你做,所以试试这个。在这种情况下,它使用我用来获取最前面运行的应用程序的子程序。只需将此代码放入您的自动化操作的 applescript 部分...

on run {input, parameters}
    if application "KeyboardViewer" is running then
        quit application "KeyboardViewer"
    else
        set frontAppPath to my getFrontAppPath()
        activate application "KeyboardViewer"
        delay 0.2
        tell application frontAppPath to activate
    end if
    return input
end run

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 1 then exit repeat
            end repeat
        end try
    end if
    return frontAppPath
end getFrontAppPath
于 2012-10-07T09:17:47.847 回答