在 Lazarus 中, 关于如何执行一个外部 command(命令)或 process(进程)或 program(程序),可以使用如下表中的方法:
方法 | Library | Platforms | 单行代码 | 功能 |
ExecuteProcess | RTL | 跨平台 | 是 | 非常有限 |
ShellExecute | WinAPI | 仅微软Windows系统 | 是 | 较多 |
fpsystem, fpexecve | Unix | 仅Unix系统 | ||
TProcess | FCL | 跨平台 | 否 | 完全 |
RunCommand | FCL | 跨平台 需要FPC 2.6.2+ | 是 | 涉及共有的TProcess用法 |
OpenDocument | LCL | 跨平台 | 是 | 仅打开文档。 |
在实际开发中,我们比较常用的是:ShellExecute、TProcess、RunCommand 和 OpenDocument 4 个方法,本节我们来学习 RunCommand,是可以跨平台的,在 Process 单元中。
RunCommand 在当前工作目录执行命令, 使用 CmdLine 的版本尝试将命令行拆分为二进制和单独的命令行参数。此版本的函数已弃用。
在 Process 单元中的 RunCommand 函数原型:
function RunCommand( const exename: TProcessString; const commands: array of TProcessString; out outputstring: string; Options: TProcessOptions = []; SWOptions: TShowWindowOptions = swoNone):Boolean;参数:
function RunCommand( const cmdline: TProcessString; out outputstring: string):Boolean;参数:
cmdline - 要启动的二进制文件的限定路径,以及由空格分隔的命令行参数
outputstring - 进程输出的字符串
函数结果:
如果函数执行成功则为 True,否则返回 False。
RunCommandInDir 将使用命令行选项 commands 执行二进制 exename,将 curdir设置为命令的当前工作目录。 捕获命令的输出,并在字符串 OutputString 中返回。该函数等待命令完成,如果命令启动成功,则返回 True ,否则返回 False。在返回值为整数的情况下,成功为零,错误为-1。如果指定了 ExitStatus 参数,则在此参数中返回命令的退出状态。
使用 cmdline 的版本尝试将命令行拆分为二进制和单独的命令行参数,此版本的函数已弃用。
在 Process 单元中的 RunCommandIndir 函数原型:
function RunCommandIndir( const curdir: TProcessString; const exename: TProcessString; const commands: array of TProcessString; out outputstring: string; out exitstatus: Integer; Options: TProcessOptions = []; SWOptions: TShowWindowOptions = swoNone):Integer;参数:
function RunCommandIndir( const curdir: TProcessString; const exename: TProcessString; const commands: array of TProcessString; out outputstring: string; Options: TProcessOptions = []; SWOptions: TShowWindowOptions = swoNone):Boolean;参数:
function RunCommandInDir( const curdir: TProcessString; const cmdline: TProcessString; out outputstring: string):Boolean;参数:
函数结果:
如果命令成功启动,则为真(或在整数返回值的情况下为零)。
错误:
出错时,返回False。
启动进程时使用的选项:
在窗体中添加两个按钮和一个 Memo 组件,单击第一个按钮在当前目录下执行 dir /s /a,单击第二个按钮在指定目录下执行 dir /s /a。代码如下:
procedure TForm1.Button1Click(Sender: TObject);var OutputString: String;begin if RunCommand('cmd', ['/c', 'dir', '/s', '/a'], OutputString) then Memo1.Lines.Add(OutputString);end;procedure TForm1.Button2Click(Sender: TObject);var OutputString: String;begin if RunCommandIndir('E:\published', 'cmd', ['/c', 'dir', '/s', '/a'], OutputString) then Memo1.Lines.Add(OutputString);end; | 留言与评论(共有 0 条评论) “” |