tags:

views:

406

answers:

2

Hello, I have run the new process using ShellExecuteEx. The process is run properly. But if I try to check the hasExited property the process threw this exception. Why is it and what to do to check if the process alive?

    ShellExecuteEx(ref info);
    clientProcessId = NativeMethods.GetProcessId(info.hProcess);
    Process clientProcess = Process.GetProcessById((int)clientProcessId);
if (clientProcess.hasExited) //<---- exception but the process is alive exactly! I can see its window
{
   //run new one
}

Thanks

A: 

likely throws an error because the object doesnt exist anymore and therefore your checking a object that is destroyed

similar issue arises in vb when dealing with pictures

function openimg(imgpath)
img = get image from path
return img
end function

that will not return an image properly for some reason

instead the line needs to be

return img.clone() to properly return the image

however thats my example

Jim
A: 

For info, did you set fMask to SEE_MASK_NOCLOSEPROCESS, so that hProcess is valid?

Also, why are you P/Invoke'ing to ShellExecuteEx, why not use Process.Start w/ ProcessStartInfo, which will handle ShellExecuteEx for you?

EDIT: Since you are doing runas, you only get SYNCHRONIZE access on the handle, not PROCESS_QUERY_INFORMATION access, hence GetExitCodeProcess fails, which results in hasEnded throwing a Win32 exception.

As a workaround, you could P/Invoke WaitForSingleObject with a timeout of zero to see if the process has exited.

Michael
sure I set the fMask else I would not be able to get the handle of the process. I use this function to be able to run the process as elevated in Vista as "runas". As I know it's the one opportunity to do so in Vista.
Seacat
Thanks, the runas explains why you're seeing this. Answer updated.
Michael