Search code examples
c#winapiwaitforsingleobject

WaitForSingleObject return ERROR_INVALID_HANDLE


I'm trying to determine if a process is still alive (at the moment I did check, I'm aware it can be closed right after I do the check) by calling WaitForSingleObject() with a handle get from Process.MainWindowHandle which works just fine with IsIconic() but it return WAIT_FAILED and GetLastError() a ERROR_INVALID_HANDLE

UInt32 r = WaitForSingleObject(handle, 0);
if(r == WAIT_OBJECT_0)
{
    MessageBox.Show("still running!");
}
if(r == WAIT_FAILED)
{
    throw new Win32Exception(Marshal.GetLastWin32Error());
}

Solution

  • You cannot wait on a window handle. You can pass window handles to window-related functions, like IsIconic(), but they are not kernel objects so you cannot wait on them. The documentation gives a list of objects that you can wait on:

    The WaitForSingleObject function can wait for the following objects:

    • Change notification
    • Console input
    • Event
    • Memory resource notification
    • Mutex
    • Process
    • Semaphore
    • Thread
    • Waitable timer

    So, if you want to wait on a process until it ends, you can wait on the process's handle, which is accessible via the Process.Handle property.

    But you don't actually need to P/Invoke the Win32 function at all. The .NET Process wrapper class has WaitForExit() and WaitForInputIdle() member functions that can be used to wait on a process (note that both have overloads taking a timeout value).

    If this is a process that you started using the Process class wrapper, you can simply interrogate the Process.HasExited property.