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

问题描述

我需要从 Delphi 软件执行 Windows查找"命令.我尝试使用 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');

感谢您的回答:)我试图将查找"作为可执行文件运行,而不是作为 cmd.exe 的参数.

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

推荐答案

一个使用 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;

请注意,使用 CreateProcess() 而不是 ShellExecute() 可以更好地控制流程.

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

理想情况下,您还可以在辅助线程中调用它,并在进程句柄上调用 WaitForSingleObject() 以等待进程完成.示例中的 Sleep() 只是为了等待由 ShellExecute() 启动的程序完成一段时间 - ShellExecute()不会那样做.如果是这样,例如您不能简单地打开 notepad 实例来编辑文件,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-10 00:26