如何在AppleScript中获取当前的finder窗口

问题描述 投票:0回答:1

我编写了下面的脚本,将自述文件添加到当前文件夹(如果还没有)。在研究如何做到这一点时,我发现了两种获取当前 Finder 位置路径的方法:

  1. target of front window
  2. insertion location

每个的用例是什么?

target of front window
在我的脚本中更合适吗?我尝试了这两个选项,但似乎没有任何差异,即使选择了当前 Finder 位置的文件夹也是如此。

tell application "Finder"
    set currentFolder to target of front window as string
    set readmePath to currentFolder & "README.md"
    
    if not (exists file readmePath) then
        do shell script "touch " & quoted form of POSIX path of readmePath
        reveal file readmePath
    else
        display dialog "README.md already exists in this folder."
    end if
end tell
applescript
1个回答
0
投票

每个 Finder 窗口都拥有自己的

target
属性。要使用该命令,您必须以某种方式指定窗口,因为它可以应用于任何打开的窗口。当然,如果没有打开任何窗口,那么使用它会产生错误。

您可以同时

get
set
窗口的
target
。后者意味着你可以改变目标。

tell application "Finder" to set winTarg to target of Finder window 1

            –or–

tell application "Finder" to set target of Finder window 1 to (path to movies folder)

由于这种灵活性,您必须确保您正在使用所需的窗口。如果在脚本运行时某些内容改变了窗口的顺序,则根据脚本的编写方式,可能会改变结果。

insertion location
是 Finder 应用程序的一项属性,虽然它会根据最前面的窗口(如果有的话)而变化,但只有一个。如果您从 Finder 的文件菜单中选择该命令,它会与创建新文件夹的位置对齐,因此不需要打开窗口。您无需指定任何内容,并且由于它是只读的,因此使用起来很简单。

tell application "Finder" to insertion location

        -or- 

tell application "Finder" to set insLoc to insertion location

在使用前窗口时,这两个命令将产生相同的结果。您可以将任一结果强制转换为所需的格式,例如 posix 路径。鉴于您当前脚本的简单性,两者都应该可以很好地使用。

© www.soinside.com 2019 - 2024. All rights reserved.