13
4

4 回答 4

10

获取path文档的属性或使用系统事件获取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。第二种方法需要启用辅助设备的访问权限。

于 2013-07-12T13:01:51.670 回答
4

我一直在使用这个片段,似乎适用于所有 Cocoa 应用程序(不确定 X11):

set front_app to (path to frontmost application as Unicode text)

tell application front_app
    -- Your code here
end tell
于 2014-08-12T07:56:25.243 回答
4

你在求...

set activeApp to name of application processes whose frontmost is true

请注意“进程”,它是复数,意思是您可以得到多个进程作为响应,因此 applescript 会为您提供一个名称列表。即使只返回一个应用程序,它仍然是列表格式。另请参阅您的错误包含 {"TextEdit"}。名称周围的括号表示它是一个列表,因此错误向您显示了问题。

您不能将名称列表传递给下一行代码。因此,您有几个选择。1)您可以只要求 1 个进程而不是所有进程。这将返回一个字符串而不是一个列表。试试这个代码...

set activeApp to name of first application process whose frontmost is true

2) 您可以使用“列表的第 1 项”来处理列表。试试这个代码...

set activeApps to name of application processes whose frontmost is true
set activeApp to item 1 of activeApps

最后,您不应该告诉系统事件来告诉应用程序。将这两个告诉代码块分开。以下是我将如何编写您的代码。

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

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

    tell me
        activate
        display dialog myPath
    end tell
on error theError number errorNumber
    tell me
        activate
        display dialog "There was an error: " & (errorNumber as text) & return & return & theError buttons {"OK"} default button 1 with icon stop
    end tell
end try

我不能保证“获取前端文件的文件”代码会起作用。这取决于应用程序。并非所有应用程序都会理解该请求。这就是我使用 try 块的原因。无论如何,尽管您可以确定您正在处理正确的应用程序。祝你好运。

于 2013-07-12T12:23:24.840 回答
0

这些似乎都不适用于保存为应用程序并放置在 Dock 上的已编译 AppleScript。每当您运行应用程序时,IT 都是最前面的,而不是显示其前窗口的应用程序。当我的 Applescript 运行时,该应用程序变为非活动状态。如何编写运行时不活动的 Applescript 应用程序?

我可能已经找到了解决上述问题的方法。只需告诉用户重新激活所需的应用程序,并给他们时间。

tell application "Finder"
   activate
   say "Click front window of your application"
   delay 5
   set myapp to get name of first application process whose frontmost is true 
-- etc.
-- your code
end tell
于 2015-01-05T18:03:24.990 回答