I am trying to get the current folder location of a Windows Explorer window. With this snippet, I am able to iterate all the windows and get their locations. However, I need to match them up to their window handles so that I can manipulate the windows style, position, parent, title, etc based on the folder location.
Alternatively, is it possible to get a InternetExplorer object from a HWND instead?
public void doStuff()
{
var t = Type.GetTypeFromProgID("Shell.Application");
var o = Activator.CreateInstance(t) as Shell32.Shell;
try
{
var ws = o.Application.Windows();
for (int i = 0; i < ws.Count; i++)
{
var ie = ws.Item(i);
if (ie == null)
continue;
var path = System.IO.Path.GetFileName((string)ie.FullName);
if (path.ToLower() != "explorer.exe")
continue;
// Gets the folder that it is showing
temp = ie.LocationURL.ToString();
temp = new Uri(temp).LocalPath;
// How can I get the window handle?
// ie.hwnd returns the top most window handle
// So if the explorer window is embedded, it returns the wrong window handle
}
}
catch (Exception x)
{
Console.log(x.Message);
}
finally
{
if (o != null)
Marshal.FinalReleaseComObject(o);
}
}
Edit:
No telling what was taking your code so long. In PowerShell, it took 90 milliseconds to retreive the
HWND-FolderPathassociation, not 15 seconds! I would expect it to be even faster in compiled code:The step-by-step approach in my answer was for the sake of comprehension. Assuming the Shell object is creaeted earlier, you just need the one line above.
I've just been working with File Explorer windows via the Shell.Application COM objects in PowerShell, so you'll have to do some code translation, but the objects, properties , and methods should be the same.
The Shell object's Windows method returns a Shellwindows object that "Represents a collection of the open windows that belong to the Shell." This contains both Internet Explorer and File Explorer ( including Control Panel ) windows:
but all window are indeed InternetExplorer objects.
The GUID of the TypeMame reveals that it's essentially a wrapper for the IWebBrowser2 interface.
It's the easily overlooked Document property that you want to access next. The link reveals why this is easy to overlook when you're in an Explorer/Shell frame-of-mnid. It exposes the following methods and properties:
But its
Folderproperty returns the Folder object for the folder displayed in the window. It's theFolderobject, along with its associated FolderItem object, that expose properties and methods associated with items in the Shell namespace. TheFolderItemis retrieved via theSelfproperty of theFolder:and it's the
Pathpropety of the FolderItem that you want.In relation to File Explorer and the Shell namespace, the path for the
FolderItemcan be ambiguous. You can determine the namespace path by recursivley eevaluating theParentFolderobject until you reach the Desktop, root of the shell namespace, which has no parent.After opening the
DOcumentesfolder from several locations: