2

I have a task killer program that has a listbox of current running processes. After an item is selected, a button click runs code to kill the selected task. That all works fine, but what I need help with is manipulating the string output on my form that displays what the last task killed was. For instance, if I open up calculator and kill that task, my string output is: "System.Diagnostics.Process (calc)". I would prefer if this was to just say "calc". So I need to be able to strip the "System.Diagnostics.Process ( )"

    public bool KillProcess(ListBox PList, TextBox Killed)
    {
        bool Kill = true;
        string x = "";
        Killed.Text = "";


        if (PList.SelectedItem != null)
        {

            foreach (Process p in Process.GetProcesses(Environment.MachineName))
            {
                x = PList.SelectedItem.ToString();

                if (p.ProcessName.Equals(x))
                {

                    try
                    {
                        p.Kill();

     //*************** Here is where I have the process killed placed into a textbox
                    //Which I would like to not say "System.Diagnostics.Process..."

                        Killed.Text = p.ToString();
                    }
                    catch
                    {
                        MessageBox.Show(p.ProcessName.ToString() + " cannot be killed. ", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        Kill = false;
                    }
                }


            }
        }
        else 
        {
            MessageBox.Show("Please select a process to be killed.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
            Kill = false;
        }

        return Kill;
    }
1
  • 4
    Why don't you simply use p.ProcessName? Commented Mar 23, 2012 at 14:42

2 Answers 2

6

Instead of

Killed.Text = p.ToString();

try

Killed.Text = p.ProcessName;

Also, as a separate note, you don’t need to say p.ProcessName.ToString() elsewhere, because p.ProcessName is already a string.

Sign up to request clarification or add additional context in comments.

1 Comment

@Richard since it works, you might want to mark this answer with a green checkbox next to it.
3

You can simply use p.ProcessName.

You could also access the p.StartInfo to get into the ProcessStartInfo which also gives you further information about the process (such as the file name) - this could be useful.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.