Get the current directory of the Finder window from the cocoa application

I am trying to get the current search box directory that is in focus from another cocoa application that is running in the background. I know that this can be done using applescript, for example:

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

However, I was wondering if there is another general way to do this, either using the accessibility API, or using a different user interface script, perhaps System Event?

I tried attributes of type NSAccessibilityDocumentAttributeor NSAccessibilityURLAttribute, but none of them are set. Of the other document-based applications, this works very well, but not for finder and for terminal.app.

+3
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);
+3

Bridge framework, , , , , Cocoa.

+2

@nkuyu, , , applescript... , ( ), .

Easily run applescript from objc using NSApplescript. And if you return the string from your applescript, it is even easier to get the result, because you can get the "stringValue" from the NSAppleEventDescriptor. Therefore, I am returning "posix paths" from applescript. Please note that NSApplescript is not thread safe, so in multi-threaded applications you should always monitor it in the main thread. Try it...

-(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);
}
+1
source

Source: https://habr.com/ru/post/1757387/


All Articles