Link to home
Start Free TrialLog in
Avatar of Andrea Matthiae
Andrea Matthiae

asked on

ShellExecute from a Delphi service but the application must be visible

Hi.
I have many problem to run a .bat (with a 'start cmd /c myapplication.exe' ) from a service. I have try ShellExecute but i have myapplication.exe running in background and never appears. My appilcation.exe is an APPTYPE CONSOLE.

I have try:
ShellExecute(0, 'open', 'c:\mydir\my.bat', nil, nil, SW_SHOWNORMAL) ;
or similar but this don't work!

I know that is difficult to execute a visual application from a service.
Can someone help me?

Windows 10
RAD Studio 10.2

Thanks in advice.
Avatar of Abhishek Sharma
Abhishek Sharma

1. Why are you not starting your program directly?
2. You can call bat file in cmd like:
ShellExecute(HInstance, PChar('open'), PChar('cmd'),
    PChar('/c "' + BatFile + '"'), PChar(ExtractFileDir(BatFile)), SW_SHOWNORMAL);

Open in new window

Avatar of Andrea Matthiae

ASKER

Hi Abhishek Sharma.

With your code the application start but is not visible; in the Windows Task Manager is in the "Backround Process list".
Yet again, did you run that exe to see if it creates console and not free it?

Also, if you're opening it via CMD, "/c" starts it and exits, try after removing it.

Also, for running it directly, try this:

procedure ShellExecAndWait(sExe, sCommandLine, sWorkDir: string;
  Wait, Freeze: Boolean; Show: Boolean = True);
var
  exInfo: TShellExecuteInfo;
  Ph: DWORD;
  WorkDir: PChar;
begin
  if sWorkDir = '' then
    WorkDir := nil
  else
    WorkDir := PChar(WorkDir);
  FillChar(exInfo, sizeof(exInfo), 0);
  with exInfo do
  begin
    cbSize := sizeof(exInfo);
    fMask := SEE_MASK_NOCLOSEPROCESS or SEE_MASK_FLAG_DDEWAIT;
    Wnd := GetActiveWindow();
    exInfo.lpVerb := 'open';
    exInfo.lpParameters := PChar(sCommandLine);
    lpFile := PChar(sExe);
    lpDirectory := WorkDir;
    nShow := SW_SHOW;
  end;
  if ShellExecuteEx(@exInfo) then
    Ph := exInfo.hProcess
  else
  begin
    exit;
  end;
  if Wait then
    while WaitForSingleObject(exInfo.hProcess, 0) <> WAIT_OBJECT_0 do
    begin
      if Freeze = false then
        Sleep(1);
    end;
  CloseHandle(Ph);
end;

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Geert G
Geert G
Flag of Belgium image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks Geert, I was hoping there is a possible solution but your answer confirms that it is impossible.