Is there a way to close a particular instance of explorer with C#?

This article that got me most of the way there: http://omegacoder.com/?p=63

I found a way using a COM library called "Microsoft Internet Controls" that looks more intended for Internet Explorer, but I gave up trying to use the process ID's and MainWindowTitle stuff since explorer.exe only uses one process for all open windows and I couldn't pin down how to get the window title text or file system location from that.

So first, add a reference to Microsoft Internet Controls from the COM tab, then:

using SHDocVw;

This little routine did the trick for me:

ShellWindows _shellWindows = new SHDocVw.ShellWindows();
string processType;

foreach (InternetExplorer ie in _shellWindows)
{
    //this parses the name of the process
    processType = Path.GetFileNameWithoutExtension(ie.FullName).ToLower();

    //this could also be used for IE windows with processType of "iexplore"
    if (processType.Equals("explorer") && ie.LocationURL.Contains(@"C:/Users/Bob"))
        {
            ie.Quit();
        }    
}

One caveat, and probably owing to the fact this library is geared toward IE, is you have to use forward slashes in your folder path... That's because the true LocationURL that comes back from the ie object is in the form file:///C:/Users/...


I would try importing user32.dll and calling FindWindow or FindWindowByCaption, followed by a call to DestroyWindow.

Info about FindWindow is here: http://www.pinvoke.net/default.aspx/user32.findwindow


This works. It's a follow up on Jeff Roe's post.

// Find window by Caption only. Note you must pass IntPtr.Zero as the first parameter.
[DllImport("user32.dll", EntryPoint = "FindWindow", SetLastError = true)]
public static extern IntPtr FindWindowByCaption(IntPtr ZeroOnly, string lpWindowName);

[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, StringBuilder lParam);

// caption is the window title.
public void CloseWindowsExplorer(string caption)
{
    IntPtr i = User32.FindWindowByCaption(IntPtr.Zero, caption);
    if (i.Equals(IntPtr.Zero) == false)
    {
        // WM_CLOSE is 0x0010
        IntPtr result = User32.SendMessage(i, 0x0010, IntPtr.Zero, null);
    }
}

Tags:

C#

Process