C# Source Code: How to automatically clean up stale processes (useful when Excel fails close properly)
[
Home
|
Contents
|
Search
|
Reply
| Previous | Next ]
C# Source Code
How to automatically clean up stale processes (useful when Excel fails close properly)
By:
Andrew Baker
Email (spam proof):
Email the originator of this post
Date:
Tuesday, July 18, 2006
Hits:
2415
Category:
General/Framework
Article:
Below is a useful console application which searches for any matching processes which that failed to terminate (ie linger after being closed). It detects the processes by checking to see if their main window handle is still valid. I use this all the time to clean up 'OUTLOOK' and 'EXCEL' processes that fail to terminate. Note, you can download this application from: http://www.vbusers.com/downloads/ProcessKillStale.zip using System; using System.Diagnostics; using System.Runtime.InteropServices; ///
/// Simple utility class for kill processes that failed to terminate. ///
class AppStaleKiller { [DllImport("USER32.DLL")] private static extern bool IsWindowVisible(IntPtr hWnd); [DllImport("user32.dll")] private static extern bool FlashWindow(IntPtr hwnd, bool bInvert); ///
/// The main entry point for the application. ///
[STAThread] static void Main(string[] args) { string processName = "EXCEL"; if ( args.Length > 0 ) { processName = args[0]; } Console.WriteLine("Searching for 'Stale' " + processName + " processes."); int killCount = 0; Process[] matchingProcs = Process.GetProcessesByName(processName); Console.WriteLine("Found " + matchingProcs.Length + " instances of '" + processName + "'."); foreach( Process proc in matchingProcs ) { Console.WriteLine("Checking process " + proc.Id + "..."); if ( !IsWindowVisible( proc.MainWindowHandle ) ) { // Kill the stale process killCount++; Console.WriteLine( processName + " with PID " + proc.Id + " is dead. Closing..."); proc.Kill(); } else { // Flash the window FlashWindow( proc.MainWindowHandle, true ); } } Console.WriteLine("Killed: " + killCount + "."); Console.WriteLine(""); Console.WriteLine("Hit [Enter] to quit..."); Console.ReadLine(); } }
Terms and Conditions
Support this site
Download a trial version of the best FTP application on the internet