C # kill processes in the system

  Before killing system processes must first know the name of the process (said something nonsense), here to note process in Task Manager name is not necessarily true name. Figuratively, we open a "notepad", the Task Manager process name is "Notepad", but actually called "notepad". If you do not know where to look, you can point to open the Task Manager, right-click the process properties view, are generally xxx.exe form.

  Then we started to write code, can be recycled into the system to take all running processes, then according to the process name and id match will be deleted, it is worth noting: open multiple "Notepad" process, name is the same, if according to the process name to kill, then it will be shut off. id is unique, but each time you start "Notepad" id will be randomly assigned.

Quote:

using System.Diagnostics;

Code:

/// <summary>
/// 杀掉FoxitReader进程
/// </summary>
/// <param name="strProcessesByName"></param>
public static void KillProcess(string processName) 
{ 
    foreach (Process p in Process.GetProcesses())            
    {
        if (p.ProcessName.Contains(processName))
        {
            try
            {
                p.Kill();
                p.WaitForExit(); // possibly with a timeout
                Console.WriteLine($"已杀掉{processName}进程!!!");
            }
            catch (Win32Exception e)
            { 
                Console.WriteLine(e.Message.ToString());    
            }
            catch (InvalidOperationException e)
            { 
                Console.WriteLine(e.Message.ToString()); 
            }
        }
        
    }
}

transfer:

KillProcess("notepad");

 

Guess you like

Origin www.cnblogs.com/swjian/p/11404142.html