本文介绍了如何在Delphi中运行命令行程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从Delphi软件执行Windows的find命令。我试图使用 ShellExecute 命令,但它似乎不工作。在C中,我将使用 system 过程,但在这里...我不知道。我想这样做:

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 the system procedure, but here... I don't know. I'd like to do something like this:

System('find "320" in.txt > out.txt');

编辑:感谢答案:)
我试图运行查找

Edit : Thanks for the answer :)I was trying to run 'Find' as an executable, not as argument for cmd.exe.

推荐答案

使用 ShellExecute() code>:

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;

请注意,使用 CreateProcess() ShellExecute()可以更好地控制进程。

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

理想情况下, ,并在进程句柄上调用 WaitForSingleObject()等待进程完成。示例中的 Sleep()只是等待一段时间由 ShellExecute()启动的程序finish - ShellExecute()不会这样做。如果你不能例如简单地打开一个记事本实例来编辑文件, ShellExecute()您的父应用程序,直到编辑器关闭。

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.

这篇关于如何在Delphi中运行命令行程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-12 21:04