简体   繁体   中英

How to scan and kill a process by name

I would like to make a program that will scan and kill a process by name. I found this:

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

The problem is that this just kills the process one time and it closes. What I want is the program to continue and kill the process again if it starts again. Any ideas?

I imagine you could use such solution:

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

and then in case when new process is started:

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

But all this is a pretty weird concept to kill the process every time it starts. I would rather try to find out the way to prevent starting but I don't know the business case of course.

You can find more on ManagementEventWatcher class here .

Create a timer that runs every X seconds or minutes that runs the code that you want like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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