I have a button on my app that once clicked launches a finder window of a specific path.
I am using this
NSString *picturesPath = [self getAppPicturesPath];
[[NSWorkspace sharedWorkspace] selectFile:nil inFileViewerRootedAtPath:picturesPath];
The problem is that if I am running the app from, lets say, display 1, the window will be launched on a random position on display 2.
How do I make that window to be launched on the same display my app is running and preferably on top of it, centered?
If your app isn't sandboxed, you can do it by setting the window's position using AppleScript. You'll need to check the frame of the screen you want, which you can do using NSScreen. For example, if I run this code (Swift, for the nicer NSRect
logging, but the equivalent in Objective-C is obvious enough) on my current setup:
import Cocoa
for eachScreen in NSScreen.screens {
print(eachScreen.frame)
}
I get:
(0.0, 0.0, 1920.0, 1200.0)
(-1440.0, -511.0, 1440.0, 900.0)
As you can see, my second screen's frame has negative coordinates, so if I move the window to something over there, like this:
tell application "Finder"
set theFolder to folder POSIX file "/usr/bin"
open theFolder
set the position of the window of theFolder to {-885, 938}
end tell
It ends up on the second screen.
If you're wondering how to actually execute the script, you have a few options there. You can use NSAppleScript
's terrible API, you can use Scripting Bridge
's terrible API, or you can make your own DIY terrible API by using NSTask
/Process
to send the script to osascript -e
.