-1

I'm creating an application that needs to check the response of some process.

System.Diagnostics.Responding doesn't works properly. So I'm trying to find a solution using windows API.

I already tried SendMessageTimeOut like this:

[DllImport("user32.dll", CharSet=CharSet.Auto)]
public static extern IntPtr SendMessageTimeout(
    IntPtr hWnd, 
    uint msg, 
    UIntPtr wParam, 
    IntPtr lParam, 
    uint flags, 
    uint timeout, 
    out IntPtr pdwResult);


public static bool IsResponding(Process process)
{
    IntPtr hProcess = IntPtr.Zero;

    try
    {
        hProcess = OpenProcess(
            ProcessAccessFlags.QueryInformation | ProcessAccessFlags.DuplicateHandle | ProcessAccessFlags.Synchronize,
            false,
            (uint)process.Id
        );

        if (hProcess == IntPtr.Zero)
            return false;

        IntPtr hResult = SendMessageTimeout(hProcess, 13, UIntPtr.Zero, IntPtr.Zero, SMTO_ABORTIFHUNG, 2000, out IntPtr pdwResult);

        return hResult != IntPtr.Zero;
    }
    catch
    {
        return false;
    }
    finally
    {
        if (hProcess != IntPtr.Zero)
            CloseHandle(hProcess);
    }
}

Other attempt was with IsHungAppWindow.

[DllImport("user32.dll", CallingConvention = CallingConvention.Winapi, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool IsHungAppWindow(IntPtr hwnd);

I really do not know why it always returns me that the application is not responding.

My PInvokes works fine, I think, don't throw anytime. And OpenProcess are working too.

I've create a WPF app that can respond and not respond every 15 sec. Task Manager can get No responding properly but my app no.

What I did wrong? All I read about advice me to use that two functions.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
Kevin Kouketsu
  • 786
  • 6
  • 20
  • Take a look at this post, I think it is pretty similar to the issue you are running into. https://stackoverflow.com/questions/3500634/how-to-check-if-process-is-not-responding – Shawn Lehner Nov 27 '18 at 16:22
  • @ShawnLehner i already read that and doesn't help me :( – Kevin Kouketsu Nov 27 '18 at 16:25
  • 1
    Note that Process.Responding also uses SendMessageTimeout with a 5000 timeout: https://github.com/Microsoft/referencesource/blob/master/System/services/monitoring/system/diagnosticts/Process.cs so you can 1) see how it's done and 2) it may not be ok for you anyway. – Simon Mourier Nov 27 '18 at 16:52

1 Answers1

3

The problem is that SendMessageTimeout and IsHungAppWindow require you to pass window handles, but you are passing process handles. Obtain a handle to the application's main window, and pass that instead.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490