我正在尝试从后台运行的另一个cocoa应用程序获取焦点窗口的当前目录。我知道可以使用AppleScript来完成它:
tell application "Finder"
try
set dir to (the target of the front window) as alias
on error
set dir to startup disk
end try
end tell
但是我想知道是否有一些更通用的方法可以使用辅助功能API或其他一些UI脚本编写System Event
?
我尝试了NSAccessibilityDocumentAttribute
或NSAccessibilityURLAttribute
等属性但未设置任何属性。从其他大多数基于文档的应用程序来看,这非常有效,但不适用于finder或terminal.app。
答案 0 :(得分:3)
// this is the finder
FinderApplication * finder = [SBApplication applicationWithBundleIdentifier:@"com.apple.Finder"];
// get all the finder windows
SBElementArray * finderWindows = finder.FinderWindows;
// this is the front window
FinderWindow * finderWindow = finderWindows[0];
// this is its folder
FinderFolder * finderFolder = finderWindow.properties[@"target"];
// this is its URL
NSString * finderFolderURL = finderFolder.URL;
NSLog(@"front window URL: %@", finderFolderURL);
答案 1 :(得分:2)
看看Scripting Bridge framework,这可能是直接从Cocoa应用程序获取所需信息的最简单方法。
答案 2 :(得分:1)
@nkuyu,我刚刚看到你的评论,你知道如何运行一个苹果...但对于那些没有(并可能偶然发现这篇文章)的人,我会解释。
使用NSApplescript从objc运行applescript很容易。如果从AppleScript返回一个字符串,则更容易获得结果,因为您可以从NSAppleEventDescriptor获取“stringValue”。因此,我从AppleScript返回“posix路径”。请注意,NSApplescript不是线程安全的,因此在多线程应用程序中,您必须注意始终在主线程上运行它。试试这个......
-(IBAction)runApplescript:(id)sender {
[self performSelectorOnMainThread:@selector(getFrontFinderWindowTarget) withObject:nil waitUntilDone:NO];
}
-(void)getFrontFinderWindowTarget {
NSString* theTarget = nil;
NSString* cmd = @"tell application \"Finder\"\ntry\nset dir to the target of the front window\nreturn POSIX path of (dir as text)\non error\nreturn \"/\"\nend try\nend tell";
NSAppleScript* theScript = [[NSAppleScript alloc] initWithSource:cmd];
NSDictionary* errorDict = nil;
NSAppleEventDescriptor* result = [theScript executeAndReturnError:&errorDict];
[theScript release];
if (errorDict) {
theTarget = [NSString stringWithFormat:@"Error:%@ %@", [errorDict valueForKey:@"NSAppleScriptErrorNumber"], [errorDict valueForKey:@"NSAppleScriptErrorMessage"]];
} else {
theTarget = [result stringValue];
}
[self getFrontFinderWindowTargetResult:theTarget];
}
-(void)getFrontFinderWindowTargetResult:(NSString*)result {
NSLog(@"result: %@", result);
}