先新建一个工程。添加控件
Timer1 //用于获取命令输入后的返回信息
Edit1 //用于输入命令
Memo1 //用于显示
如下图:
我们用CreateProcess函数来创建一个cmd进程,如下
//创建cmd 进程 并且执行 edit1.text 命令
CreateProcess(nil, PChar(edit1.Text), @Security, @Security, true,NORMAL_PRIORITY_CLASS, nil, nil, StartUpInfo, ProcessInfo);
用TerminateProcess 来释放cmd进程如下
TerminateProcess(ProcessInfo.hProcess, 0); //关闭cmd进程
用ReadFile 来读取命令返回信息 如下
ReadFile(Pipe, Buffer[0], ReadBuffer, BytesRead, nil); //读取返回信息
好了,我们来看看 关键的 创建cmd进程函数
var
Security: TSecurityAttributes;
StartUpInfo: TStartUpInfo;
begin
with Security do begin
nLength := SizeOf(TSecurityAttributes);
bInheritHandle := true;
lpSecurityDescriptor := nil;
end;
Createpipe(ReadOut, WriteOut, @Security, 0);
Createpipe(ReadIn, WriteIn, @Security, 0);
FillChar(StartUpInfo, Sizeof(StartUpInfo), #0);
StartUpInfo.cb := SizeOf(StartUpInfo);
with StartUpInfo do
begin
hStdOutput := WriteOut;
hStdInput := ReadIn;
hStdError := WriteOut;
dwFlags := STARTF_USESTDHANDLES + STARTF_USESHOWWINDOW;
wShowWindow := SW_HIDE;
end;
//创建cmd 进程 并且执行 edit1.text 命令
CreateProcess(nil, PChar(edit1.Text), @Security, @Security, true,NORMAL_PRIORITY_CLASS, nil, nil, StartUpInfo, ProcessInfo);
end;
获取命令返回函数
var
Buffer: PChar;
BytesRead: DWord;
ReadBuffer: Cardinal;
begin
Result := '';
if GetFileSize(Pipe, nil) = 0 then Exit;
Buffer := AllocMem(ReadBuffer + 1);
repeat
BytesRead := 0;
ReadFile(Pipe, Buffer[0], ReadBuffer, BytesRead, nil); //读取返回信息
if BytesRead > 0 then
begin
Buffer[BytesRead] := #0;
OemToAnsi(Buffer, Buffer);
Result := string(Buffer);
end;
until (BytesRead < ReadBuffer);
FreeMem(Buffer);
end;
运行结果如下:
源码下载