Problem with Killing windows explorer?

前端 未结 5 571
梦毁少年i
梦毁少年i 2020-12-17 02:34

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

5条回答
  •  甜味超标
    2020-12-17 02:41

    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://docs.microsoft.com/en-us/windows-server/administration/windows-commands/taskkill

提交回复
热议问题