samuraisxmali
samuraisxmali

Reputation: 103

process.kill() method doesn't work on windows 7

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

Answers (3)

Hans Passant
Hans Passant

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

Rick Strahl
Rick Strahl

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

PraveenVenu
PraveenVenu

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

Related Questions