process.kill()方法在Windows 7上不起作用 [英] process.kill() method doesn't work on windows 7

查看:200
本文介绍了process.kill()方法在Windows 7上不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从列表中杀死一个进程.因此,我首先列出了进程,然后使用process.kill().但这是行不通的.下面是代码,我不知道我做错了什么或必须做的事情. (我有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;
        }

推荐答案

            foreach (Process p in Process.GetProcesses())
            {
                string strName = listBox1.SelectedItem.ToString();

                if (p.ProcessName == strName)
                {
                    p.Kill();
                }
                listBox1.Items.Remove(strName);
            }

您的代码中存在逻辑错误.即使进程名称​​ not 不匹配,您也可以调用Remove()方法.仅当所选项目是GetProcesses()返回的第一个项目时,此代码才有效,因此可能性很小.更常见的结果是,您将在循环的第一遍将其从列表中删除,最终一无所获.使用调试器很容易看到.

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.

一个简单的解决方法是将Remove()调用移到if()语句块内.

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

这篇关于process.kill()方法在Windows 7上不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆