Here is a nice little piece of code I use. I am giving you this code but expect you to NOT just copy and paste. Please go through it to understand what it does.
The CreateProcess is what David spoke about. It is the best way to create and handle a process in Windows. Also note the WaitForSingleObject. That causes your execution to wait for Windows to finish before it returns after creating the process. You may of course remove the wait part. Also note the create flags.
It is called ExecuteAndWait. When you call it it will create a process and wait for it to finish:
function ExecuteAndWait(AFilename : String; AParameter : string;
ACmdShow : Integer; var AErrorOrExitCode : Cardinal): Boolean;
var
StartupInfo: TStartupInfo;
ProcessInfo: TProcessInformation;
S : String;
begin
FillChar(StartupInfo,Sizeof(StartupInfo),0);
StartupInfo.cb := Sizeof(StartupInfo);
StartupInfo.dwFlags := STARTF_USESHOWWINDOW;
StartupInfo.wShowWindow := ACmdShow;
S := AParameter;
UniqueString(S);
if not CreateProcess(PChar(AFilename),PChar(S),nil,nil,False,
CREATE_NEW_CONSOLE or NORMAL_PRIORITY_CLASS,nil,nil,
StartupInfo,ProcessInfo) then
begin
Result := False;
AErrorOrExitCode := GetLastError;
end
else
begin
Result := True;
WaitforSingleObject(ProcessInfo.hProcess,INFINITE);
GetExitCodeProcess(ProcessInfo.hProcess,AErrorOrExitCode);
CloseHandle(ProcessInfo.hProcess);
CloseHandle(ProcessInfo.hThread);
end;
end;
Example:
var
ErrorOrExitCode : Cardinal;
begin
If not ExecuteAndWait('c:\windows\regedit.exe','"c:\windows\regedit.exe" "c:\test.reg"',SW_SHOWDEFAULT,ErrorOrExitCode) then
Showmessage(Inttostr(ErrorOrExitCode));
Here I tell regedit to load a exported reg file. Note the double-quotes and also note that I specify the executable as the filename and as part of the parameter.
Adapt it to your needs.
ShellExecute
. It does not support sane error handling. UseShellExecuteEx
and get a proper error code. Then take it from there. However,ShellExecuteEx
is still the wrong function. You need to callCreateProcess
to do this right. – David Heffernan