It is fairly easy to close a file explorer based on its window name, like this:
msWinHelper Class:
[DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr FindWindow(string strClassName, string strWindowName);
[DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);
static uint WM_CLOSE = 0x10;
public IntPtr findWindow(string className, string name)
{
return FindWindow(className, name);
}
public void closeWindow(string className, string windowName)
{
SendMessage(findWindow(className, windowName), WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
}
Main program:
msWinHelper.closeWindow(null, "WindowName");
However in some occasions this is not sufficient. Lets say I have two directories with the same subdirectories. If I open a subdir DIR1
from parent folder FOLD1
and another DIR1
from FOLD2
, window names become the same. Therefore code cannot determine which is the parent folder and would not necessarily close the one I want.
Is it possible to close an opened folder based on its full path?
The shell has an automation interface that allows enumeration of explorer windows.
Add COM references to shell32.dll and shdocvw.dll then you can:
foreach (SHDocVw.InternetExplorer window in new SHDocVw.ShellWindows())
{
if (Path.GetFileNameWithoutExtension(window.FullName).ToLowerInvariant() == "explorer")
{
if (Uri.IsWellFormedUriString(window.LocationURL, UriKind.Absolute))
{
string location = new Uri(window.LocationURL).LocalPath;
if (string.Equals(location, @"C:\close\me", StringComparison.OrdinalIgnoreCase))
window.Quit();
}
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments