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

青春壹個敷衍的年華 提交于 2019-12-11 17:56:44

问题


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

回答1:


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



回答2:


It is because you do not have the admin previlages.

Follow the below post

programmatically kill a process in vista/windows 7 in C#




回答3:


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.



来源:https://stackoverflow.com/questions/9581017/process-kill-method-doesnt-work-on-windows-7

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!