How do I run a command-line program in Delphi?

An example using ShellExecute():

procedure TForm1.Button1Click(Sender: TObject);
begin
  ShellExecute(0, nil, 'cmd.exe', '/C find "320" in.txt > out.txt', nil, SW_HIDE);
  Sleep(1000);
  Memo1.Lines.LoadFromFile('out.txt');
end;

Note that using CreateProcess() instead of ShellExecute() allows for much better control of the process.

Ideally you would also call this in a secondary thread, and call WaitForSingleObject() on the process handle to wait for the process to complete. The Sleep() in the example is just a hack to wait some time for the program started by ShellExecute() to finish – ShellExecute() will not do that. If it did you couldn’t for example simply open a notepad instance for editing a file, ShellExecute() would block your parent app until the editor was closed.

Leave a Comment