C#流程杀戮

时间:2010-02-10 14:51:51

标签: c# winforms process kill terminate

我需要在c#中编写一个程序,它只会启动,杀死一个应该杀死并结束自身的进程\ exe。

我需要杀死的进程是另一个C#应用程序,因此它是本地用户进程,我知道 exe 的路径。

8 个答案:

答案 0 :(得分:32)

结帐Process.GetProcessesByNameProcess.Kill

// Get all instances of Notepad running on the local
// computer.
Process [] localByName = Process.GetProcessesByName("notepad");
foreach(Process p in localByName)
{
   p.Kill();
}

答案 1 :(得分:18)

首先搜索要杀死的进程的所有进程,然后再搜索它。

Process[] runningProcesses = Process.GetProcesses();
foreach (Process process in runningProcesses)
{
    // now check the modules of the process
    foreach (ProcessModule module in process.Modules)
    {
        if (module.FileName.Equals("MyProcess.exe"))
        {
            process.Kill();
        }
    }
}

答案 2 :(得分:14)

按名称杀死进程可以在C#中轻松完成(因为其他答案已经完美展现)。但是,如果你想根据可执行文件的完整路径杀死进程,则会变得更加棘手。一种方法是使用WMI,另一种方法是使用Module32First Windows API函数。

以下示例使用后一种方法。它首先按名称选择正在运行的进程的子集,然后查询每个进程的完整可执行路径。请注意,此路径将是正在执行的映像的实际路径,这不一定是已启动的可执行文件(例如,在x64系统上,calc.exe的实际路径将为C:\ Windows \ SysWOW64 \ calc.exe,即使文件C:\ Windows \ system32 \ calc.exe已启动)。具有匹配路径的所有进程都由GetProcessesByPath返回:

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;

class Program
{
    static void Main(string[] args)
    {
        Process[] processList = GetProcessesByPath(@"C:\Program Files\MyCalculator\calc.exe");
        foreach (var process in processList)
        {
            if (!process.HasExited)
                process.Kill();
        }
    }

    static Process[] GetProcessesByPath(string path)
    {
        List<Process> result = new List<Process>();

        string processName = Path.GetFileNameWithoutExtension(path);
        foreach (var process in Process.GetProcessesByName(processName))
        {
            ToolHelpHandle hModuleSnap = NativeMethods.CreateToolhelp32Snapshot(NativeMethods.SnapshotFlags.Module, (uint)process.Id);
            if (!hModuleSnap.IsInvalid)
            {
                NativeMethods.MODULEENTRY32 me32 = new NativeMethods.MODULEENTRY32();
                me32.dwSize = (uint)System.Runtime.InteropServices.Marshal.SizeOf(me32);
                if (NativeMethods.Module32First(hModuleSnap, ref me32))
                {
                    if (me32.szExePath == path)
                    {
                        result.Add(process);
                    }
                }
                hModuleSnap.Close();
            }
        }

        return result.ToArray();
    }
}

//
// The safe handle class is used to safely encapsulate win32 handles below
//
public class ToolHelpHandle : SafeHandleZeroOrMinusOneIsInvalid
{
    private ToolHelpHandle()
        : base(true)
    {
    }

    [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
    protected override bool ReleaseHandle()
    {
        return NativeMethods.CloseHandle(handle);
    }
}
//
// The following p/invoke wrappers are used to get the list of process and modules
// running inside each process.
//
public class NativeMethods
{
    [DllImport("kernel32.dll", SetLastError = true)]
    static public extern bool CloseHandle(IntPtr hHandle);

    [DllImport("kernel32.dll")]
    static public extern bool Module32First(ToolHelpHandle hSnapshot, ref MODULEENTRY32 lpme);

    [DllImport("kernel32.dll")]
    static public extern bool Module32Next(ToolHelpHandle hSnapshot, ref MODULEENTRY32 lpme);

    [DllImport("kernel32.dll")]
    static public extern bool Process32First(ToolHelpHandle hSnapshot, ref PROCESSENTRY32 lppe);

    [DllImport("kernel32.dll")]
    static public extern bool Process32Next(ToolHelpHandle hSnapshot, ref PROCESSENTRY32 lppe);

    [DllImport("kernel32.dll", SetLastError = true)]
    static public extern ToolHelpHandle CreateToolhelp32Snapshot(SnapshotFlags dwFlags, uint th32ProcessID);

    public const short INVALID_HANDLE_VALUE = -1;

    [Flags]
    public enum SnapshotFlags : uint
    {
        HeapList = 0x00000001,
        Process = 0x00000002,
        Thread = 0x00000004,
        Module = 0x00000008,
        Module32 = 0x00000010,
        Inherit = 0x80000000,
        All = 0x0000001F
    }

    [StructLayoutAttribute(LayoutKind.Sequential)]
    public struct PROCESSENTRY32
    {
        public uint dwSize;
        public uint cntUsage;
        public uint th32ProcessID;
        public IntPtr th32DefaultHeapID;
        public uint th32ModuleID;
        public uint cntThreads;
        public uint th32ParentProcessID;
        public int pcPriClassBase;
        public uint dwFlags;
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
        public string szExeFile;
    };

    [StructLayoutAttribute(LayoutKind.Sequential)]
    public struct MODULEENTRY32
    {
        public uint dwSize;
        public uint th32ModuleID;
        public uint th32ProcessID;
        public uint GlblcntUsage;
        public uint ProccntUsage;
        IntPtr modBaseAddr;
        public uint modBaseSize;
        IntPtr hModule;
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
        public string szModule;
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
        public string szExePath;
    };
}

部分代码基于Jason Zander撰写的文章here

答案 3 :(得分:3)

您可以调用Process.Kill方法

您可以使用Process.GetProcesses获取所有流程或Process.GetProcessByNameProcess.GetProcessById,以便您可以启动流程来致电。

答案 4 :(得分:2)

Process[] processes = Process.GetProcesses();
foreach (Process pr in processes){ 
  if (pr.ProcessName=="vfp")
    if (pr.MainWindowTitle.Contains("test"))
      pr.CloseMainWindow();
}`enter code here`

这里的vfp是进程名称。和测试是设置标题名称。

答案 5 :(得分:1)

您可以使用Process Class类来实现它,但为什么要杀死另一个进程?

答案 6 :(得分:1)

进程类有Kill()方法

答案 7 :(得分:0)

我想定义自己要关闭的应用程序列表,所以我根据我列出的一些示例做了这个。它简单而有效。

        string[] Process_name_list = {"chrome","notepad"};
        foreach (string Process_name in Process_name_list)
        {
            foreach (var process in Process.GetProcessesByName(Process_name))
            {                    
                process.Kill();
            }
        }