简体   繁体   English

在ListBox中显示所有正在运行的应用程序,并在c#中单击按钮将其杀死

[英]Show all running applications in ListBox and kill them on button click in c#

I want to collect processes in listbox like this: 我想像这样在列表框中收集进程:

app.exe otherapp.exe app.exe otherapp.exe

but I just get: 但我得到:

System.Diagnostics.Process(app.exe) System.Diagnostics.Process(otherapp.exe) System.Diagnostics.Process(app.exe)System.Diagnostics.Process(otherapp.exe)

My code: 我的代码:

    private void Form1_Load(object sender, EventArgs e)
    {
        Process[] prs = (Process.GetProcesses());

        foreach (Process pr in prs)
        {
            listBox1.Items.Add(Convert.ToString(pr));
        }
    }

    private void button3_Click(object sender, EventArgs e)
    {
        Process[] prs = Process.GetProcesses();

        string item = Convert.ToString(listBox1.SelectedItem);

        //item.Kill();
    }

First you should store the process name: 首先,您应该存储进程名称:

    foreach (Process process in Process.GetProcesses())
    {
        listBox1.Items.Add(process.ProcessName);
    }

After that you can use the name to get the process(es) and kill it/them: 之后,您可以使用该名称来获取进程并将其杀死:

    Process[] processes = Process.GetProcessesByName(listBox1.SelectedItem.ToString());

    foreach (Process process in processes)
    {
        process.Kill();
    }

See https://msdn.microsoft.com/en-us/library/system.diagnostics.process(v=vs.110).aspx for more information about the process class. 有关流程类的更多信息,请参见https://msdn.microsoft.com/en-us/library/system.diagnostics.process(v=vs.110).aspx

You can use the same code just a small change 您只需很小的改动就可以使用相同的代码

 listBox1.Items.Add(Convert.ToString(pr.ProcessName));

So in short 简而言之

  private void Form1_Load(object sender, EventArgs e)
{
 Process[] prs = (Process.GetProcesses());

             foreach (Process pr in prs)
             {

                listBox1.Items.Add(Convert.ToString(pr.ProcessName));
             }
}

Output: 输出:

在此处输入图片说明

Reason: 原因:

You just had to use the Property ProcessName property on the Instance 您只需要在实例上使用Property ProcessName属性

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM