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.
Delphi

Avatar of undefined
Last Comment
Andrea Matthiae

8/22/2022 - Mon
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

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".
Abhishek Sharma

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

Experts Exchange is like having an extremely knowledgeable team sitting and waiting for your call. Couldn't do my job half as well as I do without it!
James Murphy
ASKER CERTIFIED SOLUTION
Geert G

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Andrea Matthiae

ASKER
Thanks Geert, I was hoping there is a possible solution but your answer confirms that it is impossible.