How to use CreateProcess API Call to create and execute a new process in Delphi XE4?
How to use CreateProcess API Call to create and execute a new process in Delphi XE4?
procedure ExecuteNewProcess(ProgramName : String; Wait: Boolean);
var
StartInfo : TStartupInfo;
ProcInfo : TProcessInformation;
CreateOK : Boolean;
begin
FillChar(StartInfo,SizeOf(TStartupInfo),#0);
FillChar(ProcInfo,SizeOf(TProcessInformation),#0);
StartInfo.cb := SizeOf(TStartupInfo);
CreateOK := CreateProcess(nil, PChar(ProgramName), nil, nil,False,
CREATE_NEW_PROCESS_GROUP+NORMAL_PRIORITY_CLASS,
nil, nil, StartInfo, ProcInfo);
try
if CreateOK then //Check if the process is created successfully
begin
if Wait then WaitForSingleObject(ProcInfo.hProcess, INFINITE); //Load children processes
end
else
begin
ShowMessage('Unable to run '+ProgramName);
end;
finally
CloseHandle(ProcInfo.hProcess);
CloseHandle(ProcInfo.hThread);
end;
end;
In above code, I will pass an executable file to ExecuteNewProcess method lets say abc.exe.
Relation between Threads and Processes
Executing a program or process in Win32 means loading a process and its child thread(s) in memory. CreateProcess is used to create and run the process in Win32. We will see how to use CreateProcess in Delphi XE4 to execute an exe? For backward compatibility, the Win16 calls for executing programs, WinExec and ShellExecute are still supported in the Windows API, and still work. But for 32-bit programs, they're considered obsolete.
The following code utilizes the CreateProcess API call, and will execute any program, DOS or Windows.
procedure ExecuteNewProcess(ProgramName : String; Wait: Boolean);
var
StartInfo : TStartupInfo;
ProcInfo : TProcessInformation;
CreateOK : Boolean;
begin
FillChar(StartInfo,SizeOf(TStartupInfo),#0);
FillChar(ProcInfo,SizeOf(TProcessInformation),#0);
StartInfo.cb := SizeOf(TStartupInfo);
CreateOK := CreateProcess(nil, PChar(ProgramName), nil, nil,False,
CREATE_NEW_PROCESS_GROUP+NORMAL_PRIORITY_CLASS,
nil, nil, StartInfo, ProcInfo);
try
if CreateOK then //Check if the process is created successfully
begin
if Wait then WaitForSingleObject(ProcInfo.hProcess, INFINITE); //Load children processes
end
else
begin
ShowMessage('Unable to run '+ProgramName);
end;
finally
CloseHandle(ProcInfo.hProcess);
CloseHandle(ProcInfo.hThread);
end;
end;
In above code, I will pass an executable file to ExecuteNewProcess method lets say abc.exe.
Relation between Threads and Processes
Here it is very important to mention the relation between threads and processes. Threads are children of processes; while processes, on the other hand, are inert system entities that essentially do absolutely nothing but define a space in memory for threads to run - threads are the execution portion of a process and a process can have many threads attached to it. So, we can say, processes are merely memory spaces for threads.