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

前端 未结 2 801
梦毁少年i
梦毁少年i 2020-11-30 04:37

I need to execute a Windows \"find\" command from a Delphi software. I\'ve tried to use the ShellExecute command, but it doesn\'t seem to work. In C, I\'d use t

2条回答
  •  一整个雨季
    2020-11-30 05:27

    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.

提交回复
热议问题