C# 进程终止

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2237628/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-07 00:39:23  来源:igfitidea点击:

C# Process Killing

c#winformsprocesskillterminate

提问by Moon

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的路径。

采纳答案by Simon Linder

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

回答by Giorgi

You can achieve it by using Process Classclass but why would you want to kill another process?

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

回答by Anton Setiawan

Process class has Kill() method

进程类有 Kill() 方法

回答by Sam Holder

you can call the Process.Killmethod

你可以调用Process.Kill方法

you can use the Process.GetProcessesto get all processes or Process.GetProcessByNameor Process.GetProcessByIdso you can get the process to call Kill on.

您可以使用Process.GetProcesses来获取所有进程或 Process.GetProcessByNameProcess.GetProcessById以便您可以让进程调用 Kill。

回答by SwDevMan81

Check out Process.GetProcessesByNameand 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();
}

回答by Dirk Vollmar

Killing processes by their name can be easily done in C# (as the other answers already showed perfectly). 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 Module32FirstWindows API function.

在 C# 中可以很容易地按名称杀死进程(因为其他答案已经完美显示)。但是,如果您想根据可执行文件的完整路径终止进程,事情就会变得更加棘手。一种方法是使用 WMI,另一种方法是使用Module32FirstWindows 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 (e.g. 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). All processes with a matching path are returned by GetProcessesByPath:

下面的示例使用后一种方法。它首先按名称选择正在运行的进程的子集,然后查询每个进程的完整可执行路径。请注意,此路径将是正在执行的映像的实际路径,它不一定是启动的可执行文件(例如,在 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;
    };
}

Some of the code is based on an article by Jason Zander which can be found here.

部分代码基于 Jason Zander 的一篇文章,可在此处找到。

回答by vishal paliwal

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. and test is setup title name.

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

回答by user2673536

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