0

I am looking for a way to close a File explorer window programmatically using C#. I am writing an automation script and I am stuck in the scenario where I have to close a File explorer after selecting a file. Selenium doesn't work with Window-based forms. So is there a way that I can accomplish the task of closing the File Explorer window using C#.

The answer mentioned in the below link doesn't work for me. Is there a way to close a particular instance of explorer with C#?

Zmehak
  • 11
  • 4
  • 3
    _"The answer mentioned in the below link doesn't work for me."_. Why? – Adriano Repetti May 07 '20 at 08:12
  • 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/mm")) { ie.Quit(); } } – Zmehak May 07 '20 at 08:21
  • Added this bit of the code but the window is not closing. Sadly. – Zmehak May 07 '20 at 08:21
  • @Andriano I have few points to mention here, the process I want to kill is a File Explorer window and I am not using Internet Explorer as my browser. – Zmehak May 07 '20 at 09:00
  • 1
    I do not see how Internet Explorer has anything to do with this. explorer.exe is the Windows Explorer executable. – Adriano Repetti May 07 '20 at 09:03
  • Yea because in the code you are using the InternetExplorer interface to grab the filename. – Zmehak May 07 '20 at 09:06
  • You're not using IE for that, you're using some COM objects designed to be used _by_ IE and scripts. Object names are weird and misleading (for compatibility, sigh) but they're in shell32dll – Adriano Repetti May 07 '20 at 09:37
  • The file dialog is part of the common dialog dll (comdlg32.dll). This dialog is called from languages like c# and vbnet as well as from windows. It has many options which is why it may appear to look different in applications. When you open it in windows there is no handle that is returned so the only way of closing is to find the process name and kill the process. In your case it may be better to open in c# as a Open File Name or call it using the Process Class in c# so you can close it without have to kill a process. – jdweng May 07 '20 at 10:01

1 Answers1

0

I found the solution!

        Process[] myProcess = Process.GetProcesses();
        for (int i = 0; i < myProcess.Length; i++)
        {
            if (myProcess[i].ProcessName == "explorer")
            {
                Thread.Sleep(2000);
                myProcess[i].Kill();
                break;
            }
        } 
Zmehak
  • 11
  • 4