如何使用AppleScript获取最前端应用程序的名称并使用它来获取文件路径 [英] How to get name of frontmost app with AppleScript and use it to get the filepath

查看:136
本文介绍了如何使用AppleScript获取最前端应用程序的名称并使用它来获取文件路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要做什么:

当我使用一个文本编辑器(TextEdit,Byword,FoldingText)时,我希望此AppleScript显示文件路径.

When I'm in one of my text editors (TextEdit, Byword, FoldingText) I want this AppleScript to display the file path.

我想知道最前端的窗口应用程序会让我得到这些应用程序的名称,并且很容易,然后我可以在下一步中请求POSIX路径.

I figured asking for the frontmost window app get's me the apps name nice and easily and then I can ask for the POSIX path in the next step.

问题:

该脚本已经存在99%,但我缺少一些内容.当我尝试使用变量activeApp时,它不起作用,并且出现此错误:

The script is already 99% there, but I'm missing something. When I try to use the variable of activeApp it doesn't work and I get this error:

Error Number:System Events got an error: Can’t get application {"TextEdit"}.
-1728

这是脚本:

tell application "System Events"
     set activeApp to name of application processes whose frontmost is true

     --This doesn't work either:
     --do shell script "php -r 'echo urldecode(\"" & activeApp & "\");'"

     tell application activeApp
         set myPath to POSIX path of (get file of front document)
     end tell
     display dialog myPath
end tell

如果我将activeApp"TextEdit"交换,则一切正常.帮助将不胜感激.

If I exchange activeApp with "TextEdit" everything works. Help would be appreciated.

也许这里有些帮助:推荐答案

要么获取文档的path属性,要么使用系统事件获取value of attribute "AXDocument":

Either get the path property of a document or use System Events to get value of attribute "AXDocument":

try
    tell application (path to frontmost application as text)
        (path of document 1) as text
    end tell
on error
    try
        tell application "System Events" to tell (process 1 where frontmost is true)
            value of attribute "AXDocument" of window 1
        end tell
        do shell script "x=" & quoted form of result & "
        x=${x/#file:\\/\\/}
        x=${x/#localhost} # 10.8 and earlier
        printf ${x//%/\\\\x}"
    end try
end try

第一种方法不适用于Preview,TextMate 2,Sublime Text或iChm,第二种方法不适用于Acorn.第二种方法要求启用辅助设备的访问权限.

The first method didn't work with Preview, TextMate 2, Sublime Text, or iChm, and the second method didn't work with Acorn. The second method requires access for assistive devices to be enabled.

这篇关于如何使用AppleScript获取最前端应用程序的名称并使用它来获取文件路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆