简体   繁体   English

C#进程杀

[英]C# Process Killing

I need to write a program in c# that would just start, kill one process\exe that it is supposed to kill and end itself.我需要在 c# 中编写一个程序,它会启动、终止一个它应该终止并自行结束的进程\exe。

The process I need to kill is another C# application so it is a local user process and I know the path to the exe .我需要终止的进程是另一个 C# 应用程序,因此它是一个本地用户进程,我知道exe的路径。

Check out Process.GetProcessesByName and Process.Kill 查看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();
}

First search all processes for the process you want to kill, than kill it. 首先搜索要杀死的进程的所有进程,然后再搜索它。

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();
        }
    }
}

Killing processes by their name can be easily done in C# (as the other answers already showed perfectly). 按名称杀死进程可以在C#中轻松完成(因为其他答案已经完全显示)。 If you however want to kill processes based on the full path of the executable things get more tricky. 但是,如果你想根据可执行文件的完整路径杀死进程,则会变得更加棘手。 One way to do that would be to use WMI, another way would be to use the Module32First Windows API function. 一种方法是使用WMI,另一种方法是使用Module32First Windows API函数。

The sample below uses the latter approach. 以下示例使用后一种方法。 It first selects a subset of the running processes by their name and then queries each of these processes for their full executable path. 它首先按名称选择正在运行的进程的子集,然后查询每个进程的完整可执行路径。 Note that this path will be the actual path of the image being executed, which is not necessarily the executable that was launched (eg on x64 systems the actual path to calc.exe will be C:\\Windows\\SysWOW64\\calc.exe even if the file C:\\Windows\\system32\\calc.exe was started). 请注意,此路径将是正在执行的映像的实际路径,这不一定是已启动的可执行文件(例如,在x64系统上,calc.exe的实际路径将为C:\\ Windows \\ SysWOW64 \\ calc.exe,即使文件C:\\ Windows \\ system32 \\ calc.exe已启动)。 All processes with a matching path are returned by GetProcessesByPath : 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;
    };
}

Some of the code is based on an article by Jason Zander which can be found here . 一些代码基于Jason Zander撰写的文章,可以在这里找到。

you can call the Process.Kill method 你可以调用Process.Kill方法

you can use the Process.GetProcesses to get all processes or Process.GetProcessByName or Process.GetProcessById so you can get the process to call Kill on. 您可以使用Process.GetProcesses获取所有进程或Process.GetProcessByNameProcess.GetProcessById,以便您可以获取调用Kill的进程。

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

Here vfp is process name. 这里的vfp是进程名称。 and test is setup title name. 和测试是设置标题名称。

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

进程类有Kill()方法

I wanted to define my own list of applications to close so I made this based on some of the examples I've seen listed. 我想定义自己要关闭的应用程序列表,所以我根据我列出的一些示例做了这个。 It's simple and effective. 它简单而有效。

        string[] Process_name_list = {"chrome","notepad"};
        foreach (string Process_name in Process_name_list)
        {
            foreach (var process in Process.GetProcessesByName(Process_name))
            {                    
                process.Kill();
            }
        }
 string[] Process_name_list = { "RobloxPlayerBeta", "RobloxPlayerLauncherBeta", "RobloxPlayer", "RobloxPlayerLauncher", "RobloxStudio", "RobloxStudioBeta", "RobloxStudioLauncher", "RobloxStudioLauncherBeta" };
            foreach (string Process_name in Process_name_list)
            {
                foreach (var process in Process.GetProcessesByName(Process_name))
                {
                    process.Kill();
                }
            }

Replace the Roblox processes with anything you want.用您想要的任何东西替换 Roblox 进程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM