如何按名称扫描和终止进程

时间:2016-01-27 21:18:24

标签: c#

我想创建一个程序,它将按名称扫描并终止进程。我发现了这个:

foreach (Process process in Process.GetProcessesByName("vlc"))
{
    process.Kill();
    process.WaitForExit();
}

问题在于,这只会杀死一次并关闭。我想要的是程序如果再次启动则继续并再次终止该进程。有什么想法吗?

2 个答案:

答案 0 :(得分:5)

我想你可以使用这样的解决方案:

private ManagementEventWatcher WatchForProcessStart(string processName)
{
    string queryString =
        "SELECT TargetInstance" +
        "  FROM __InstanceCreationEvent " +
        "WITHIN  10 " +
        " WHERE TargetInstance ISA 'Win32_Process' " +
        "   AND TargetInstance.Name = '" + processName + "'";

    // The dot in the scope means use the current machine
    string scope = @"\\.\root\CIMV2";

    // Create a watcher and listen for events
    ManagementEventWatcher watcher = new ManagementEventWatcher(scope, queryString);
    watcher.EventArrived += ProcessStarted;
    watcher.Start();
    return watcher;
}

然后在新流程启动时:

private void ProcessStarted(object sender, EventArrivedEventArgs e)
{
  //Here kill the process.
}

但是这一切都是一个非常奇怪的概念,每次启动都会杀死进程。我宁愿尝试找出防止启动的方法,但我当然不知道商业案例。

您可以在ManagementEventWatcher类here上找到更多信息。

答案 1 :(得分:1)

创建一个每X秒或几分钟运行一次的计时器,运行您想要的代码:

public static void Main()
{
    System.Timers.Timer timer = new System.Timers.Timer();
    timer.Elapsed += (source, srgs) =>
    {
        foreach (Process process in Process.GetProcessesByName("vlc"))
        {
            process.Kill();
            process.WaitForExit();
        }

        //Start again. 
        //This makes sure that we wait 10 seconds after
        //we are done killing the processes
        timer.Start();
    };

    //Run every 10 seconds
    timer.Interval = 10000; 

    //This causes the timer to run only once
    //But will be restarted after processing. See comments above
    timer.AutoReset = false;

    timer.Start();

    Console.WriteLine("Press any key to exit");
    Console.ReadLine();
}