Reputation: 103
I want to kill a process from list. Because of this I first list the processes and then use process.kill()
. But it doesn't work. Below is the code and I don't know what I'm doing wrong or what I have to do. (I have Windows 7). Can you help?
private void btnProcess_Click(object sender, EventArgs e)
{
UpdateProcessList();
}
private void btnRemove_Click(object sender, EventArgs e)
{
try
{
foreach (Process p in Process.GetProcesses())
{
string strName = listBox1.SelectedItem.ToString();
if (p.ProcessName == strName)
{
p.Kill();
}
listBox1.Items.Remove(strName);
}
UpdateProcessList();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void UpdateProcessList()
{
listBox1.Items.Clear();
foreach (Process p in Process.GetProcesses())
{
listBox1.Items.Add(p.ProcessName);
}
listBox1.Sorted = true;
}
Upvotes: 0
Views: 5653
Reputation: 941465
foreach (Process p in Process.GetProcesses())
{
string strName = listBox1.SelectedItem.ToString();
if (p.ProcessName == strName)
{
p.Kill();
}
listBox1.Items.Remove(strName);
}
There's a logical error in your code. You call the Remove() method even if the process name does not match. This code can only work if the selected item is the first one returned by GetProcesses(), very low odds for that. The far more common outcome is that you'll remove the item from the list on the very first pass through the loop and end up killing nothing. Easy to see with a debugger.
A simple workaround is to move the Remove() call inside the if() statement block.
An entirely better approach is:
foreach (var p in Process.GetProcessesByName(listBox1.SelectedItem.ToString()) {
p.Kill();
}
Upvotes: 4
Reputation: 17651
In order to kill a process you have to run under an administrative account. This means either that you are a 'true' administrator or you User Account Control (UAC) turned off.
Otherwise Process.Kill() will fail.
Upvotes: 0
Reputation: 8337
It is because you do not have the admin previlages.
Follow the below post
programmatically kill a process in vista/windows 7 in C#
Upvotes: 0