Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get folder path from Explorer window

Tags:

c#

.net

winapi

I have a pointer to an opened Explorer Window and i want to know its full path.

For Example:

int hWnd = FindWindow(null, "Directory");

But now, how to obtain the directory full path like "C:\Users\mm\Documents\Directory"

like image 377
mmarques Avatar asked Jan 06 '14 22:01

mmarques


People also ask

How do you copy a folder path as a link?

If you're using Windows 10, hold down Shift on your keyboard and right-click on the file, folder, or library for which you want a link. If you're using Windows 11, simply right-click on it. Then, select “Copy as path” in the contextual menu.

What is the path to a folder?

A path is a slash-separated list of directory names followed by either a directory name or a file name. A directory is the same as a folder.


1 Answers

Here's a way to obtain that information:

    IntPtr MyHwnd = FindWindow(null, "Directory");
    var t = Type.GetTypeFromProgID("Shell.Application");
    dynamic o = Activator.CreateInstance(t);
    try
    {
        var ws = o.Windows();
        for (int i = 0; i < ws.Count; i++)
        {
            var ie = ws.Item(i);
            if (ie == null || ie.hwnd != (long)MyHwnd) continue;
            var path = System.IO.Path.GetFileName((string)ie.FullName);
            if (path.ToLower() == "explorer.exe")
            {
                var explorepath = ie.document.focuseditem.path;
            }
        }
    }
    finally
    {
        Marshal.FinalReleaseComObject(o);
    } 

Adapted from this: http://msdn.microsoft.com/en-us/library/windows/desktop/bb773974(v=vs.85).aspx

Cheers

EDIT: I changed ie.locationname, which was not returning the full path, to ie.document.focuseditem. path, which seems to be working so far.

like image 160
Luc Morin Avatar answered Sep 26 '22 12:09

Luc Morin