Windows – Why does explorer restart automatically when I kill it with Process.Kill

.net frameworkckillprocesswindows-explorer

If I kill explorer.exe like this:

private static void KillExplorer()
{
    var processes = Process.GetProcessesByName("explorer");
    Console.Write("Killing Explorer... ");
    foreach (var process in processes)
    {
        process.Kill();
        process.WaitForExit();
    }
    Console.WriteLine("Done");
}

It restarts immediately.

But if I use taskkill /F /IM explorer.exe, or kill it from the task manager, it doesn't restart.

Why is that? What's the difference? How can I close explorer.exe from code without restarting it? Sure, I could call taskkill from my code, but I was hoping for a cleaner solution…

Best Answer

I can't say that I haven't cheated to get the answer. All credits go to morguth for his post here.

What he has suggested (and proved work on my Win7 and XPMode) is that there is a registry key that forces the shell to restart automatically. By using the following code you disable that.

RegistryKey ourKey = Registry.LocalMachine;
ourKey = ourKey.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon", true);
ourKey.SetValue("AutoRestartShell", 0);
// Kill the explorer by the way you've post and do your other work
ourKey.SetValue("AutoRestartShell", 1)
Related Question