Tuesday, February 13, 2018

DELPHI - How to call external program

This code execute external program (FFileName as path, FParams as optional parameters). It uses ShellExecuteEx(), in old Windows (XP and older) you can use ShellExecute() too.
function TExecute.Execute : THandle;
var 
  iShowCmd : integer;  
  b : boolean;
  exInfo : SHELLEXECUTEINFO;
begin

  iShowCmd := sw_ShowNormal;
  case FShowType of
    stNormal         : iShowCmd := sw_ShowNormal;
    stMaximized      : iShowCmd := sw_ShowMaximized;
    stMinimize       : iShowCmd := sw_Minimize;
    stHide           : iShowCmd := sw_Hide;
    stRestore        : iShowCmd := sw_Restore;
    stShow           : iShowCmd := sw_Show;
    stShowMinimized  : iShowCmd := sw_ShowMinimized;
    stShowNA         : iShowCmd := sw_ShowNA;
    stShowNoActivate : iShowCmd := sw_ShowNoActivate;
  end;

  { -- run it }

  exInfo.cbSize := sizeof( SHELLEXECUTEINFO );
  exInfo.fMask := SEE_MASK_NOCLOSEPROCESS; 
  exInfo.wnd := Application.Handle;
  exInfo.lpVerb := pchar( 'open' ); 
  exInfo.lpFile := pchar( FFileName );
  exInfo.lpParameters := pChar( FParams );
  exInfo.nShow := SW_SHOWNORMAL;
  //exInfo.hInstApp = NULL;
  //exInfo.lpDirectory = NULL;

  b := ShellExecuteEx( @exInfo );

  SetWindowPos(result, HWND_TopMost, 0, 0, 0, 0, SWP_NoMove or SWP_NoSize);

  if not b then ShowMessage( 'Execute problem: ' + IntToStr( GetLastError ) );

  result := GetLastError;
end;

No comments:

Post a Comment