简体   繁体   English

如何从Delphi运行命令行?

[英]How to run command line from Delphi?

How can I run this command from my Delphi application? 如何从我的Delphi应用程序中运行此命令?

C:\\myapppath\\appfolder>appname.exe /stext save.txt C:\\ myapppath \\ appfolder> appname.exe / stext save.txt

I tried the following code: 我尝试了以下代码:

ShellExecute(0, nil, 'cmd.exe', 'cd C:\myapppath\appfolder', nil, SW_Hide);
ShellExecute(0, nil, 'cmd.exe', 'appname.exe /stext save.txt', nil, SW_Hide);

But it didn't work. 但这没有用。 Can anyone provide a solution? 谁能提供解决方案?

To run a CMD command, you need to use the /C flag of cmd.exe : 要运行CMD命令,您需要使用cmd.exe/C标志:

ShellExecute(0, nil, 'cmd.exe', '/C cd C:\myapppath\appfolder', nil, SW_HIDE);
ShellExecute(0, nil, 'cmd.exe', '/C appname.exe /stext save.txt', nil, SW_HIDE);

However, this will create two different sessions, so it will not work. 但是,这将创建两个不同的会话,因此它将不起作用。 But you can use ShellExecute to run appname.exe directly, like so: 但是您可以使用ShellExecute直接运行appname.exe ,如下所示:

ShellExecute(0, nil, 'appname.exe',  '/stext save.txt', nil, SW_HIDE);

But you need to specify the filenames properly. 但是您需要正确指定文件名。

I would do 我会做

var
  path: string;

begin
  path := ExtractFilePath(Application.ExeName);
  ShellExecute(0, nil, PChar(Application.ExeName), PChar('/stext "' + path + 'save.txt"'), nil, SW_HIDE);
end;

in case appname.exe is the current application. 如果appname.exe是当前应用程序。 Otherwise, replace Application.ExeName with the full path of appname.exe . 否则,将Application.ExeName替换为appname.exe的完整路径。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM