通过.exe文件名杀死一些进程

发布于 2024-09-11 19:22:17 字数 49 浏览 6 评论 0原文

如何通过在 C# .NET 或 C++ 中搜索 .exe 文件名来终止某些活动进程?

How can I kill some active processes by searching for their .exe filenames in C# .NET or C++?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

与往事干杯 2024-09-18 19:22:26
public void EndTask(string taskname)
{
      string processName = taskname.Replace(".exe", "");

      foreach (Process process in Process.GetProcessesByName(processName))
      {
          process.Kill();
      }
}

//EndTask("notepad");

总结:无论名称中是否包含.exe,进程都会结束。您不需要“从进程名称中删除 .exe”,它可以 100% 工作。

public void EndTask(string taskname)
{
      string processName = taskname.Replace(".exe", "");

      foreach (Process process in Process.GetProcessesByName(processName))
      {
          process.Kill();
      }
}

//EndTask("notepad");

Summary: no matter if the name contains .exe, the process will end. You don't need to "leave off .exe from process name", It works 100%.

棒棒糖 2024-09-18 19:22:25
static void Main()
    {
        string processName = Process.GetCurrentProcess().ProcessName;
        int processId = Process.GetCurrentProcess().Id;
        
        Process[] oProcesses = Process.GetProcessesByName(processName);

        if (oProcesses.Length > 1)
        {
            if ((MessageBox.Show("Application is opened!", "",MessageBoxButtons.YesNo) == DialogResult.Yes)) ;
            {
                foreach (var process in Process.GetProcessesByName(processName))
                {
                    if (process.Id != processId)
                    {
                        process.Kill();
                    }
                }
            }
        }
        else
        {   
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new frmLogin());
        }
    }
static void Main()
    {
        string processName = Process.GetCurrentProcess().ProcessName;
        int processId = Process.GetCurrentProcess().Id;
        
        Process[] oProcesses = Process.GetProcessesByName(processName);

        if (oProcesses.Length > 1)
        {
            if ((MessageBox.Show("Application is opened!", "",MessageBoxButtons.YesNo) == DialogResult.Yes)) ;
            {
                foreach (var process in Process.GetProcessesByName(processName))
                {
                    if (process.Id != processId)
                    {
                        process.Kill();
                    }
                }
            }
        }
        else
        {   
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new frmLogin());
        }
    }
信仰 2024-09-18 19:22:24

就我而言,我想确保抓住正确的过程......;-)

所以我这样做:

private static void KillProcessesByPath(string fullExePath)
{
  var processName = Path.GetFileNameWithoutExtension(fullExePath);

  foreach (var process in Process.GetProcessesByName(processName))
  {
    if (process.MainModule?.FileName != fullExePath) continue;

    process.Kill();
  }
}

For my part, I wanted to be sure to catch the right process... ;-)

So I do:

private static void KillProcessesByPath(string fullExePath)
{
  var processName = Path.GetFileNameWithoutExtension(fullExePath);

  foreach (var process in Process.GetProcessesByName(processName))
  {
    if (process.MainModule?.FileName != fullExePath) continue;

    process.Kill();
  }
}
三月梨花 2024-09-18 19:22:23

您可以终止 MS Word 的特定实例。

foreach (var process in Process.GetProcessesByName("WINWORD"))
{
    // Temp is a document which you need to kill.
    if (process.MainWindowTitle.Contains("Temp")) 
        process.Kill();
}

You can Kill a specific instance of MS Word.

foreach (var process in Process.GetProcessesByName("WINWORD"))
{
    // Temp is a document which you need to kill.
    if (process.MainWindowTitle.Contains("Temp")) 
        process.Kill();
}
梦太阳 2024-09-18 19:22:22

根据要杀死的进程数量(例如,像我的情况那样有数百个进程),遍历所有进程可能需要相当长的时间。 (有趣的旁注:虽然 Kill() 在 .NET FW 4.8 中通常很快,但不知怎的,在 NET 6.0 Windows 中它要慢得多 - 在调试/跟踪中看到多个 Win32Exceptions 直到目标进程最终完成)

无论如何回到主题:
如果应用程序关闭,您需要确保每个进程都消失了,请考虑使用 TAP 库 - 特别是并行快捷方式,数百个进程一目了然。

使用示例:

var procs = Process.GetProcessByName("mydirtyprocesses");

if (procs.Length == 0) return;

procs.AsParallel().ForAll(process => 
{
   try
   {
      process.Kill();

   // No process linked to the process comp (mostly because the process died in 
   // the short timespan between invoking GetProcess() and the effective 
   // initialization of the props/fields of the component. -OR- Process has 
   // already exited (when the exit happened after the process component has 
   // beenpopulated (difference is, in case 1 you cannot even get the Process 
   // ID from // the component, in case 2 you see data like Id and get the true 
   // for HasExited // - so always be prepared for that.
   // catch (InvalidOperationException) 
   {
     // Process is gone, no further action required
     return;
   }

   // Ensuring process is gone (otherwise try again or fail or whatever)
   if (!process.HasExited)
   { 
       // Handle it
   }
}

在这个特定场景中,只需将其正确包装在 try/catch 中,因为处理数量如此之多,发生异常的概率会大大增加

Depending on how many processes there are to kill (e.g. when its hundreds like in my case), foreaching over all of them might take quite a while. (interesting sidenote: while Kill() was usually quite quick in .NET FW 4.8 , somehow in NET 6.0 Windows its a lot slower - seeing multiple Win32Exceptions in the debug/trace until the target process is finally done)

Anyway back to topic:
In case of an app shutdown, where u need to make sure every process is is gone, consider using the TAP library - particulary the Parallel shortcuts, hundreds of processes killed within a glimpse.

Usage example:

var procs = Process.GetProcessByName("mydirtyprocesses");

if (procs.Length == 0) return;

procs.AsParallel().ForAll(process => 
{
   try
   {
      process.Kill();

   // No process linked to the process comp (mostly because the process died in 
   // the short timespan between invoking GetProcess() and the effective 
   // initialization of the props/fields of the component. -OR- Process has 
   // already exited (when the exit happened after the process component has 
   // beenpopulated (difference is, in case 1 you cannot even get the Process 
   // ID from // the component, in case 2 you see data like Id and get the true 
   // for HasExited // - so always be prepared for that.
   // catch (InvalidOperationException) 
   {
     // Process is gone, no further action required
     return;
   }

   // Ensuring process is gone (otherwise try again or fail or whatever)
   if (!process.HasExited)
   { 
       // Handle it
   }
}

In this particular scenario just wrap it properly in try/catch , as with such a number of processes the probability for an exception is quite increased

凉城凉梦凉人心 2024-09-18 19:22:22

如果您有进程 ID (PID),您可以按如下方式终止该进程:

Process processToKill = Process.GetProcessById(pid);
processToKill.Kill();

If you have the process ID (PID) you can kill this process as follow:

Process processToKill = Process.GetProcessById(pid);
processToKill.Kill();
挽容 2024-09-18 19:22:21

我的解决方案是使用 Process.GetProcess() 用于列出所有进程。

通过过滤它们以包含我想要的进程,我可以运行 Process.Kill() 方法来阻止它们:

var chromeDriverProcesses = Process.GetProcesses().
    Where(pr => pr.ProcessName == "chromedriver"); // without '.exe'
    
foreach (var process in chromeDriverProcesses)
{
     process.Kill();
}

更新:

如果您想在异步中执行相同的操作方式(使用 C# 8 异步枚举),请查看:

const string processName = "chromedriver"; // without '.exe'
await Process.GetProcesses()
             .Where(pr => pr.ProcessName == processName)
             .ToAsyncEnumerable()
             .ForEachAsync(p => p.Kill());

注意:使用async 方法并不总是意味着代码会运行得更快。
主要好处是前台线程在运行时会被释放。

My solution is to use Process.GetProcess() for listing all the processes.

By filtering them to contain the processes I want, I can then run Process.Kill() method to stop them:

var chromeDriverProcesses = Process.GetProcesses().
    Where(pr => pr.ProcessName == "chromedriver"); // without '.exe'
    
foreach (var process in chromeDriverProcesses)
{
     process.Kill();
}

Update:

In case if you want to do the same in an asynchronous way (using the C# 8 Async Enumerables), check this out:

const string processName = "chromedriver"; // without '.exe'
await Process.GetProcesses()
             .Where(pr => pr.ProcessName == processName)
             .ToAsyncEnumerable()
             .ForEachAsync(p => p.Kill());

Note: using async methods doesn't always mean code will run faster.
The main benefit is that the foreground thread will be released while operating.

南城追梦 2024-09-18 19:22:21

您可以使用 Process.GetProcesses()要获取当前正在运行的进程,请使用 Process。 Kill() 终止进程。

You can use Process.GetProcesses() to get the currently running processes, then Process.Kill() to kill a process.

叹倦 2024-09-18 19:22:20

快速回答:

foreach (var process in Process.GetProcessesByName("whatever"))
{
    process.Kill();
}

(从进程名称中删除 .exe)

Quick Answer:

foreach (var process in Process.GetProcessesByName("whatever"))
{
    process.Kill();
}

(leave off .exe from process name)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文