delphi 獲取cmd命令返回並顯示(筆記)
阿新 • • 發佈:2019-01-26
先新建一個工程。新增控制元件
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;
執行結果如下:
原始碼下載