Problem with Killing windows explorer?
Asked Answered
C

5

6

I need to kill windows explorer's process (explorer.exe), for that

lets say i use a native NT method TerminateProcess

It works but the problem is that the explorer starts again, may be windows is doing that, anyway. When i kill explorer.exe with windows task manager, it doesn't come back, its stays killed.

I want to do whatever taskmanager is doing through my application.

Edit:
Thanks to @sblom i solved it, a quick tweak in the registry did the trick. Although its a clever hack, apparently taskmnager has a cleaner way of doing that, that said, i've decided to go with @sblom's way for now.

Cutanddried answered 3/4, 2010 at 4:40 Comment(0)
S
9

The "real" solution. (Complete program. Tested to work on Windows 7.)

using System;
using System.Runtime.InteropServices;

namespace ExplorerZap
{
    class Program
    {
        [DllImport("user32.dll")]
        public static extern int FindWindow(string lpClassName, string lpWindowName);
        [DllImport("user32.dll")]
        public static extern int SendMessage(int hWnd, uint Msg, int wParam, int lParam);

        [return: MarshalAs(UnmanagedType.Bool)]
        [DllImport("user32.dll", SetLastError = true)]
        public static extern bool PostMessage(int hWnd, uint Msg, int wParam, int lParam);

        static void Main(string[] args)
        {
            int hwnd;
            hwnd = FindWindow("Progman", null);
            PostMessage(hwnd, /*WM_QUIT*/ 0x12, 0, 0);
            return;
        }
    }
}
Sweyn answered 3/4, 2010 at 5:48 Comment(1)
This solution doesn't work. It closes the desktop and taskbar, but doesn't actually stop the explorer.exe process.Luing
S
15

From Technet:

You can set the registry key HKLM\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\AutoRestartShell to 0, and it will no longer auto-restart.

Sweyn answered 3/4, 2010 at 4:50 Comment(2)
@Sweyn Great ! thanks man it works, one little mystery although your workaround works perfectly. taskmanager does not seem to mess with registry settings like this. Now please please dont take it personally i was just wondering. Your answer was a life saver, as i needed it urgentlyCutanddried
@Sweyn just to give other people a chance to solve that taskmanager mystery i leave your anwser as un-accepted for a little while. I'll do that eventually !Cutanddried
S
9

The "real" solution. (Complete program. Tested to work on Windows 7.)

using System;
using System.Runtime.InteropServices;

namespace ExplorerZap
{
    class Program
    {
        [DllImport("user32.dll")]
        public static extern int FindWindow(string lpClassName, string lpWindowName);
        [DllImport("user32.dll")]
        public static extern int SendMessage(int hWnd, uint Msg, int wParam, int lParam);

        [return: MarshalAs(UnmanagedType.Bool)]
        [DllImport("user32.dll", SetLastError = true)]
        public static extern bool PostMessage(int hWnd, uint Msg, int wParam, int lParam);

        static void Main(string[] args)
        {
            int hwnd;
            hwnd = FindWindow("Progman", null);
            PostMessage(hwnd, /*WM_QUIT*/ 0x12, 0, 0);
            return;
        }
    }
}
Sweyn answered 3/4, 2010 at 5:48 Comment(1)
This solution doesn't work. It closes the desktop and taskbar, but doesn't actually stop the explorer.exe process.Luing
R
5

Here's another solution to this problem - instead api calls it uses an external tool shipped with windows (at least Win 7 Professional):

    public static class Extensions
    {
        public static void ForceKill(this Process process)
        {
            using (Process killer = new Process())
            {
                killer.StartInfo.FileName = "taskkill";
                killer.StartInfo.Arguments = string.Format("/f /PID {0}", process.Id);
                killer.StartInfo.CreateNoWindow = true;
                killer.StartInfo.UseShellExecute = false;
                killer.Start();
                killer.WaitForExit();
                if (killer.ExitCode != 0)
                {
                    throw new Win32Exception(killer.ExitCode);
                }
            }
        }
    }

I know that Win32Exception may not be the best Exception, but this method acts more or less like Kill - with the exception that it actually kills windows explorer.

I've added it as an extension method, so you can use it directly on Process object:

    foreach (Process process in Process.GetProcessesByName("explorer"))
    {
        process.ForceKill();
    }

You must first ensure that the taskkill tool is available on production environment (it seems that it's been for a while with windows: https://web.archive.org/web/20171016213040/http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/taskkill.mspx?mfr=true).

EDIT: Original link dead, replaced with cache from Internet Archive Wayback Machine. Updated documentation for Windows 2012/2016 can be found at: https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/taskkill

Resorcinol answered 21/10, 2012 at 17:2 Comment(0)
B
2

What you probably need to do is instead of using TerminateProcess, post a WM_QUIT message to the explorer windows and main thread. It's a bit involved, but I found this page which has some example code that might help you along:

http://www.replicator.org/node/100

Windows will automatically restart explorer.exe after a TerminateProcess so that it restarts in the case of a crash termination.

Brag answered 3/4, 2010 at 5:23 Comment(0)
G
0

I have some researches and these are reslts:

Windows will restart explorer after it closed -except by Task Manager-.

So you should change the related RegistryKey:

RegistryKey regKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Default).OpenSubKey(@"Software\Microsoft\Windows NT\CurrentVersion\Winlogon", RegistryKeyPermissionCheck.ReadWriteSubTree);
if (regKey.GetValue("AutoRestartShell").ToString() == "1")
    regKey.SetValue("AutoRestartShell", 0, RegistryValueKind.DWord);

For changing a registry key the program should run as administrator:

  • You can show UAC prompt to user to run application as administrator as explaining in this Answer. And if UAC is turned off I direct you to this Answer.
  • You can embed a manifest file in the exe, which will cause Windows Seven to always run the program as an administrator, As explaining in this Answer.
  • You should know you can't force your process starts as administrator; so you can run your process inside your process as another process! You can use this blog post or this answer.
  • You can also use reg command with this [Microsoft Windows Documentation].6.

After setting that -restarting explorer- off: This code can close explorer :

Process[] ps = Process.GetProcessesByName("explorer");
foreach (Process p in ps)
    p.Kill();
Graciagracie answered 9/3, 2015 at 15:45 Comment(1)
I add my answer just as a result of what I done for same problem ;).Graciagracie

© 2022 - 2024 — McMap. All rights reserved.