Recipe 8.5. Determining Whether a Process Has Stopped RespondingProblemYou need to watch one or more processes to determine whether the user interface has stopped responding to the system. This functionality is similar to the column in the TaskManager that displays the text Responding or Not Responding, depending on the state of the application. SolutionUse the method and enumeration shown in Example 8-2 to determine whether a process has stopped responding. Example 8-2. Determining whether a process has stopped responding
DiscussionThe IsProcessResponding method accepts a single parameter, process, identifying a process. The Responding property is then called on the Process object represented by the process parameter. This property returns a ProcessRespondingState enumeration value to indicate that a process is currently responding (Responding), that it is not currently responding (NotResponding), or that response cannot be determined for this process as there is no main window handle (Unknown)… The Responding property always returns true if the process in question does not have a MainWindowHandle. Processes such as Idle, spoolsv, Rundll32, and svchost do not have a main window handle and therefore the Responding property always returns true for them. To weed out these processes, you can use the MainWindowHandle property of the Process class, which returns the handle of the main window for a process. If this property returns zero, the process has no main window. To determine whether all processes on a machine are responding, you can call the IsProcessResponding method as follows: MyObject.ProcessRespondingState state; foreach (Process proc in Process.GetProcesses()) { state = MyObject.IsProcessResponding(proc); if (state == MyObject.ProcessRespondingState.NotResponding) { Console.WriteLine("{0} is not responding.",proc.ProcessName); } } This code snippet iterates over all processes currently running on your system. The static GetProcesses method of the Process class takes no parameters and returns an array of Process objects with information for all processes running on your system. Each Process object is then passed in to your IsProcessResponding method to determine whether it is responding. Other static methods on the Process class that retrieve Process objects are GetProcessById, GetCurrentProcess, and GetProcessesByName. See AlsoSee the "Process Class" topic in the MSDN documentation. |