Search code examples
delphishellexecuteex

open and close an external program from Delphi


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


Solution

  • 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