July 9, 2010

Close or Kill a Process

This routine will try and close a process by sending a close message to it's main window. If the process has no GUI or a timeout period is exceeded then the 'Process.Kill()' method will be used to close it.
// Try and close a process. Kill it if the Close takes 
// too long.
// exeLessExtension - Process name (without extension)
// msToWaitForCloseMainWindow - Time in milliseconds to
// wait for 'CloseMainWindow()' before just killing the 
// process, Set negative to not kill at all, set to 0 to 
// kill without calling CloseMainWindow
public static void ForceProcessClose(
  string exeLessExtension, 
  int msToWaitForCloseMainWindow)
{
  Process[] processes = Process.GetProcessesByName(exeLessExtension);

  if (msToWaitForCloseMainWindow != 0)
  {
    foreach (Process p in processes)
    {
      if (!p.CloseMainWindow())
      {   // Process does not have a GUI, use 'Kill()' instead
         msToWaitForCloseMainWindow = 0;
      }
    }
  }
  if (msToWaitForCloseMainWindow >= 0)
  {
    Thread.Sleep(msToWaitForCloseMainWindow);
    processes = Process.GetProcessesByName(exeLessExtension);
    foreach (Process p in processes)
    {
       p.Kill();
    }
  }
}

No comments: