Reputation: 35
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?
Upvotes: 2
Views: 881
Reputation: 1015
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.
Upvotes: 5
Reputation: 27861
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();
}
Upvotes: 1