0

I want to kill the multiple processes but also want to keep some specific ones. Actually I have two list box one has the list of processes that I want to kill. The other one has the list which I want to keep.

For example, I want to kill Google Chrome and keep the Calculator on. But the problem with this code is, it's closing all processes even the winform itself.

private void BtnStop_Click(object sender, EventArgs e)
{
 Process[] processes = Process.GetProcesses();
  foreach (Process p in processes)
   {
    if (!String.IsNullOrEmpty(p.MainWindowTitle))
    {
//ChBlockApp is the name of the list box that i want to kill
      ChBlockApp.Items.Add(p.MainWindowTitle);
                  
      try 
          {
    // ListAllowed is the name of listbox which i want to keep
 if (p.MainWindowTitle != "Avid-Main Page" | p.MainWindowTitle != ListAllowed.items.toString())
     {
    
      p.Kill();
      }
}
catch (Exception KillExc)
                            
 {
MessageBox.Show("Unable to Close the Applicaiton: " + KillExc, "Warning", MessageBoxButtons.OK,MessageBoxIcon.Warning);
}
}
}
}

I have tried using a check to keep the visual studio open in this statement.

if (p.MainWindowTitle != "Avid-Main Page")
                            {}

But it didn't work either.

This Link has some hints but i have multiple programs to keep.

Uniquedesign
  • 423
  • 1
  • 7
  • 23
  • What's with this line... `p.MainWindowTitle != ListAllowed.items.toString()`? This is checking the Title is equal to the `Items` object name which is, `System.Windows.Forms.ListBox+ObjectCollection`. These will never match. In addition, the capitalization of these properties will cause compilation to fail, `items.toString()`. – quaabaam Aug 17 '20 at 17:50
  • I tried to foreach these items but that's also not working/ – Uniquedesign Aug 17 '20 at 18:50

1 Answers1

0

Your logic is wrong on this line:

if (p.MainWindowTitle != "Avid-Main Page" |
    p.MainWindowTitle != ListAllowed.items.toString())

It should be:

if (p.MainWindowTitle != "Avid-Main Page" &&
    !ListAllowed.Items.OfType<string>().Any(x => x == p.MainWindowTitle))

You have to iterate through the items in your list. Linq makes this easy for us by implementing Any. It will loop through your items and check if any satifies the predicate.

Also, if you use | and not ||, you are using the bitwise or. You probably don't want to do that. Typically in these scenarios if the first one is false, you don't need to validate the other case and it should just fall through at that point.

In this specific case I changed it to && because then it easier to understand:

"If the title doesn't equal "Avid-Main Page" AND the title isn't in our list, then kill the program"

Andy
  • 12,859
  • 5
  • 41
  • 56