ShellExecute,我怎么能告诉我的项目应用程序已关闭?

时间:2016-04-26 15:50:57

标签: delphi delphi-xe7 shellexecute

如果我从delphi应用程序中调用ShellExecute,

如何判断我调用的程序是否已完成,以便我可以在完成其他程序后返回我的应用程序并执行其他操作。

例如,打开记事本,完成后关闭它, 在我的应用程序中显示消息“完成!”

1 个答案:

答案 0 :(得分:1)

您需要将ShellExecuteExSEE_MASK_NOCLOSEPROCESS一起使用。看看这个,看看我的评论内联:

var
    sei: TShellExecuteInfo;
    exitCode: Cardinal;
begin
    ZeroMemory(@sei, SizeOf(sei));
    with sei do
    begin
        cbSize := SizeOf(sei);
        fMask := SEE_MASK_NOCLOSEPROCESS; // Tell ShellExecuteEx to keep the process handle open
        Wnd := WindowHandleIfNeeded; // Can be omitted
        lpVerb := 'open';
        lpFile := PChar(PathOfExeToRun);
        lpParameters := PChar(ParametersToUse);
        lpDirectory := PChar(WorkingDirectoryToUse); // Can be omitted
        nShow := SW_NORMAL; // Can be omitted
    end;

    if ShellExecuteEx(@sei) then
    begin
        // I have encapsulated the different ways in begin/end and commented.

        // *** EITHER: Wait for the child process to close, without processing messages (if you do it in a background thread)
        begin
            WaitForSingleObject(sei.hProcess, INFINITE);
        end;

        // *** OR: Wait for the child process to close, while processing messages (if you do it in the UI thread)
        begin
            while MsgWaitForMultipleObjects(1, sei.hProcess, FALSE, INFINITE, QS_ALLINPUT) = (WAIT_OBJECT_0 + 1) do begin
                Application.ProcessMessages
            end;
        end;

        // *** OR: Do something else, and in the middle you can check whether the child is still running using this:
        begin
            GetExitCodeProcess(sei.hProcess, exitCode);
            if exitCode == STILL_ACTIVE then begin
                // It's still running!
            end else begin
                // It has finished!
            end;
        end;

        // At the end, close the handle
        CloseHandle(sei.hProcess);
    end; 
end;