Search code examples
c#processlistboxitems

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

but I just get:

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

Solution

  • 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:

    enter image description here

    Reason:

    You just had to use the Property ProcessName property on the Instance