如何使用 AppleScript 获取最前面的应用程序的名称并使用它来获取文件路径 [英] How to get name of frontmost app with AppleScript and use it to get the filepath
问题描述
我尝试做的事情:
当我使用其中一种文本编辑器(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.
也许这里有一些帮助:从应用程序名称获取进程名称,反之亦然,使用Applescript
推荐答案
获取文档的path
属性或使用系统事件获取属性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屋!