Michal B.
Michal B.

Reputation: 5719

How to close window created with Process.Start()

I open file explorer window from my application. I do it in the following manner:

var si = new ProcessStartInfo("explorer.exe", Path);
si.UseShellExecute = true;
var p = Process.Start(si);
p.WaitForInputIdle();
_hwnd = Window.FindWindow("CabinetWClass", null);

That part works. Now, the p.HasExited is already true. I am not sure why is that, but I assume that file explorer is not an ordinary process.

Anyway, I tried p.Close(), p.CloseMainWindow(), p.Kill() and nothing worked

I also imported DestroyWindow:

[DllImport("user32.dll", SetLastError = true)]
public static extern bool DestroyWindow(IntPtr hWnd);

and used it like this:

var result = Window.DestroyWindow(_hwnd);

but that has no effect either (_hwnd is a correct non-zero handle)...

How can I close this window?

Upvotes: 1

Views: 278

Answers (1)

usr
usr

Reputation: 171246

Destroying other processes resources unexpectedly causes unpredictable behavior... Also, you are relying on details like window classes here. Very unstable code, I hope I will never get this product onto my machine.

Anyway, you can "steer" Windows Explorer using reliable and documented APIs using COM. I'm very rusty with this technique but I can point you in the right direction: http://www.codeproject.com/Articles/12029/Automate-the-Active-Windows-Explorer-or-Internet-E (The article is both about IE and Windows Explorer because they share lots of common infrastructure).

.NET can use the COM APIs, too. The code sometimes looks much more nicely then.

Upvotes: 1

Related Questions