6.6. Determining Whether a Process Has Stopped Responding

Problem

You need to watch one or more processes to determine whether they have stopped responding to the system. This functionality is similar to the column in the Task Manager that displays the text Responding or Not Responding, depending on the state of the application.

Solution

Use the following method to determine whether a process has stopped responding:

public bool IsProcessResponding(Process process)
{
    if (process.MainWindowHandle == IntPtr.Zero)
    {
        Console.WriteLine("This process does not have a MainWindowHandle");
        return (true);
    }
    else
    {
        // This process has a MainWindowHandle
        if (!process.Responding)
        {
            Console.WriteLine("Process " + process.ProcessName + 
              " is not responding.");
            return (false);
        }
        else
        {
            Console.WriteLine("Process " + process.ProcessName + 
              " is responding.");
            return (true);
        }
    }
}

Discussion

The 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 true to indicate that a process is currently responding, or a false to indicate that the process has stopped responding.

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, ...

Get C# Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.