open and close an external program from Delphi

JimPapas picture JimPapas · May 22, 2016 · Viewed 7.6k times · Source

in my app (Delphi XE10) i want to open a file (RTF) with user's default editor (MSword or OpenOffice writter or else) and be able to close this editor from my app. I tried to use the code bellow but without success on closing the editor

procedure TForm1.Button1Click(Sender: TObject);
var hApp : Cardinal;
begin
    hApp := StartApp('open','temp.rtf','','',sw_normal);
    anotherForm.showmodal;
    KillProcess(hApp);
end;

where:

function StartApp(apchOperation, apchFileName, apchParameters, apchDirectory: PChar;awrdShowCmd: Word): Cardinal;
var
    lseiInfo: TShellExecuteInfo;
begin
    Result := 0;
    FillChar(lseiInfo, SizeOf(lseiInfo), Chr(0));
    lseiInfo.cbSize := SizeOf(lseiInfo);
    lseiInfo.fMask := SEE_MASK_NOCLOSEPROCESS;
    lseiInfo.lpVerb := apchOperation;
    lseiInfo.lpFile := apchFileName;
    lseiInfo.lpParameters := apchParameters;
    lseiInfo.lpDirectory := apchDirectory;
    lseiInfo.nShow := awrdShowCmd;
    if Boolean(ShellExecuteEx(@lseiInfo)) then
    Result := lseiInfo.hProcess;
end;

procedure   KillProcess(hProcess: Cardinal);
Var
  ovExitCode: LongWord;
begin
    try
        if hProcess <> 0 then begin
            GetExitCodeProcess(hProcess, ovExitCode);
            if (ovExitCode = STILL_ACTIVE) or (ovExitCode <> WAIT_OBJECT_0) then
            TerminateProcess(hProcess, ovExitCode);
            CloseHandle(hProcess);
        end;
    except
    end;
end;

The editor opens but when it must close with KillProcess, ovExitCode is allways zero so TerminateProcess doesn't execute. I also try to execute TerminateProcess at any case but the editor (MSword in this case) doesn't close.

Can you help me please ? thanks in advance

Answer

ViRuSTriNiTy picture ViRuSTriNiTy · May 23, 2016

I suggest dropping the KillProcess approach and use SendMessage() with WM_CLOSE instead. This way your application will exit in a "normal" way. You can get the window handle from the process handle, it is described here: https://stackoverflow.com/a/20163705/3936440