gpt4 book ai didi

objective-c - 查找当前事件的 Finder 窗口/文件夹

转载 作者:太空狗 更新时间:2023-10-30 03:59:46 27 4
gpt4 key购买 nike

有什么方法可以确定 Finder 中当前事件的窗口或文件夹?在某种意义上,我需要它来确定一个合适的“默认”位置,以便在我的应用中执行某些特定操作。

其实,这个问题还有意义吗? “当前事件的 Finder 窗口/文件夹”这个概念是否首先存在?如果没有,请问如何获取当前选定 Finder 项目。

最佳答案

是的,当前事件的 Finder 窗口的概念确实存在,以及当前选中的项目。

例如,以下 AppleScript 获取 selection,这是最前面窗口中的当前选择。由于这会返回一个文件或文件夹列表,即使只有一个项目,下一行会从该列表中获取第一个项目(在确保列表的计数大于 0 之后)。然后,您可以向 Finder 询问所选项目的 container window,这将返回一个 Finder window 对象。

tell application "Finder"
set selectedItems to selection

if ((count of selectedItems) > 0) then
set selectedItem to (item 1 of selectedItems) as alias
container window of selectedItem
end if

end tell

我很确定 sidyll 发布的代码在 10.5 和更早版本中可以正常工作,但由于 AppleScript 从一个版本的 OS X 到下一个版本似乎不可避免的变化和古怪之处,它在 10.6 中出错.

[编辑] 实际上,我只是弄清楚发生了什么。我通常会一直打开 Finder 的检查器窗口(通过 Command-Option-i 获得的动态获取信息窗口),下图中的右上面板:

enter image description here

该图像显示了 3 种不同类别的窗口:

1)左上角,一个Get Info窗口,是一个信息窗口,它继承自通用的window类。

2) 右上角,一个 Inspector 窗口,是一个普通的 window

3) 下图显示了一个 Finder 窗口,它继承自通用 window 类。

如果我使用上面显示的窗口设置运行以下脚本:

tell app "Finder"
every window
end tell

它返回以下结果:

{window "mdouma46 Info" of application "Finder", information window "mdouma46 Info" of application "Finder", Finder window id 1141 of application "Finder"}

因此,在我的案例中发生的事情是,由于检查器窗口是一个 float 实用程序面板,如果它当前正在显示,则向 Finder 询问 window 1 将始终返回检查器面板,因为它总是漂浮在其他窗口的前面。

所以我在运行代码时遇到的错误是:

error "Can’t make «class fvtg» of window 1 of application \"Finder\" into type alias." number -1700 from «class fvtg» of window 1 to alias

(换句话说,Inspector 窗口,一个普通的窗口,没有 FileViewer 目标 (fvtg) 属性;只有 Finder 窗口s 做)。

因此,只要用户没有最前面的检查器窗口、首选项窗口或获取信息窗口,您的代码就可以正常工作。但是,通过将 window 更改为 Finder 窗口,您可以确保只查看具有 target 属性的文件查看器窗口。

所以,像这样:

NSDictionary *errorMessage = nil;

NSAppleScript *script = [[[NSAppleScript alloc] initWithSource:
@"tell application \"Finder\"\n"
" if ((count of Finder windows) > 0) then\n"
" return (POSIX path of (target of Finder window 1 as alias))\n"
"end if\n"
"end tell"] autorelease];

if (script == nil) {
NSLog(@"failed to create script!");
return nil;
}
NSAppleEventDescriptor *result = [script executeAndReturnError:&errorMessage];
if (result) {
// POSIX path returns trailing /'s, so standardize the path
NSString *path = [[result stringValue] stringByStandardizingPath];
return path;
}

关于objective-c - 查找当前事件的 Finder 窗口/文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6237983/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com