加速AppleScript UI脚本?

时间:2014-01-21 22:20:19

标签: applescript

我正在使用NetShade作为代理服务,并且我认为我可以尝试在不同代理之间自动切换,这是我第一个AppleScript脚本的良好开端。

NetShade-app没有AppleScript支持,因此我必须使用UI脚本。经过几次尝试(以及此处的一些帖子)后,我设法创建了一个脚本,通过菜单栏项切换代理(此处为picture,因为我无法通过信誉限制将其发布到内联)。

不幸的是我的代码非常慢(≈6sec),这使得它作为一个脚本变得不切实际。第一个菜单立即打开,但子菜单和代理服务器的选择需要几秒钟。

我正在使用以下代码:

set theProxy to "Netshade US 4"
tell application "System Events" to tell process "NetShade"
    tell menu bar item 1 of menu bar 2
        click
        tell menu item "NetShade Proxy" of menu 1
            click
            tell menu item theProxy of menu 1
                click
            end tell
        end tell
    end tell
end tell

我已经尝试添加ignoring application responses,就像在另一个帖子(link)中建议的那样,但这没有帮助。

最后我的问题: 有没有办法加快这个过程?也许甚至可以在后台完成所有这些操作而不显示菜单项?

P.S。:我正在运行OS X 10.9.1

1 个答案:

答案 0 :(得分:5)

修复摘要

要消除延迟,您需要做两件事:

(I)确定导致延迟的点击,并仅在ignoring application responses块中包含该行,如下所示。就我而言,它是click bt,之后执行进入等待模式5到6秒。

  ignoring application responses
        click bt
  end ignoring

(II)然后我还必须使用以下命令杀死系统事件并再次启动它。

  do shell script "killall System\\ Events"
  delay 0.1  
  -- Rest of the code to click stuff or send keycodes

这解决了延迟问题。

详细信息

我遇到了同样的问题,我创建了一个脚本来通过AppleScript连接/断开我的蓝牙耳机。脚本如下。

tell application "System Events" to tell process "SystemUIServer"
    set bt to (first menu bar item whose description is "bluetooth") of menu bar 1
    click bt
    tell (first menu item whose title is "SBH80") of menu of bt
        click
        tell menu 1
            if exists menu item "Disconnect" then
                click menu item "Disconnect"
            else
                click menu item "Connect"
            end if
        end tell
    end tell
end tell

脚本工作正常,但是在执行&#34之后会等待5到6秒的问题;点击bt"以上。我修改了如下代码,它现在完全正常,没有任何延迟。

tell application "System Events" to tell process "SystemUIServer"

    set bt to (first menu bar item whose description is "bluetooth") of menu bar 1
    ignoring application responses
        click bt
    end ignoring
end tell

do shell script "killall System\\ Events"
delay 0.1
tell application "System Events" to tell process "SystemUIServer"

    tell (first menu item whose title is "SBH80") of menu of bt
        click
        tell menu 1
            if exists menu item "Disconnect" then
                click menu item "Disconnect"
            else
                click menu item "Connect"
            end if
        end tell
    end tell
end tell