Is there any way to determine the currently active window, or a folder, in the Finder? I need this to determine, in some sense, an appropriate “default” location in which to do some particular things in my app.
Actually, does this question even make sense? Does this concept of a “currently active Finder window/folder” even exist in the first place? If it does not, I kindly ask how to get the currently selected Finder item.
Yes, the concept of the currently active Finder window does exist, as well as the currently selected item.
For example, the following AppleScript gets the
selectionwhich is the current selection in the frontmost window. Since this returns a list of files or folders even if there is a single item, the next line gets the first item out of that list (after making sure that the count of the list is greater than 0). You can then ask the Finder for thecontainer windowof the selected item, which will return aFinder windowobject.I’m pretty sure the code sidyll posted will work okay in 10.5 and earlier, but it errors out in 10.6 due to the inevitable changes and quirkiness that AppleScript seems to have from one version of OS X to the next.[EDIT] Actually, I just figured out what’s going on.
I usually have the Finder’s Inspector window open all the time (the dynamic Get Info window you get through Command-Option-i), the upper right panel in the image below:
That image shows 3 different classes of windows:
1) The upper left, a Get Info window, is an
information window, which inherits from the genericwindowclass.2) The upper right, an Inspector window, is a plain
window.3) The lower image shows a
Finder window, which inherits from the genericwindowclass.If I run the following script with the setup of windows shown above:
it returns the following result:
So, what was happening in my case is that, since the Inspector window is a floating utility panel, if it’s currently being shown, asking the Finder for
window 1will always return the Inspector panel, since it’s always floating in front of the other windows.So the error I was getting when running the code was:
(In other words, the Inspector window, a plain
window, doesn’t have the FileViewer target (fvtg) property; onlyFinder windows do).So, your code will work fine as long as the user doesn’t have the Inspector window, the Preferences window, or a Get Info window that is frontmost. By changing
windowtoFinder window, though, you can make sure that you only look at the file viewer windows that have thetargetproperty.So, like this: