Delphi 通过CMD命令实现 ADB 操作


procedure TForm1.Button2Click(Sender: TObject);
var
hReadPipe, hWritePipe: THandle;
si: STARTUPINFO;
lsa: SECURITY_ATTRIBUTES;
pi: PROCESS_INFORMATION;
mDosScreen: String;
cchReadBuffer: DWORD;
ph: PansiChar;
fname: PChar;
i, j: integer;
str, TEMP, ip: string;
K: integer;
begin
Memo1.Clear;
fname := allocmem(255);
ph := allocmem(5000);
lsa.nLength := sizeof(SECURITY_ATTRIBUTES);
lsa.lpSecurityDescriptor := nil;
lsa.bInheritHandle := true;
try
try
if CreatePipe(hReadPipe, hWritePipe, @lsa, 0) = false then
begin
ShowMessage('Can not create pipe!');
exit;
end;
fillchar(si, sizeof(STARTUPINFO), 0);
si.cb := sizeof(STARTUPINFO);
si.dwFlags := (STARTF_USESTDHANDLES or STARTF_USESHOWWINDOW);
si.wShowWindow := SW_HIDE;
si.hStdOutput := hWritePipe;
StrPCopy(fname, 'adb devices'); // 显示android设备列表
if CreateProcess(nil, fname, nil, nil, true, 0, nil, nil, si, pi) = false
then
begin
ShowMessage('can not create process');
FreeMem(ph);
FreeMem(fname);
exit;
end;
while (true) do
begin
if not PeekNamedPipe(hReadPipe, ph, 1, @cchReadBuffer, nil, nil) then
break;
if cchReadBuffer <> 0 then
begin
if ReadFile(hReadPipe, ph^, 4096, cchReadBuffer, nil) = false then
break;
ph[cchReadBuffer] := chr(0);
if ph <> '' then
Memo1.Lines.Add(ph);
end
else if (WaitForSingleObject(pi.hProcess, 0) = WAIT_OBJECT_0) then
break;
Application.ProcessMessages;
Sleep(100);
end;
ph[cchReadBuffer] := chr(0);
if ph <> '' then
Memo1.Lines.Add(StringReplace(ph, #13#10, '', [rfReplaceAll]));
CloseHandle(hReadPipe);
CloseHandle(pi.hThread);
CloseHandle(pi.hProcess);
CloseHandle(hWritePipe);
FreeMem(ph);
FreeMem(fname);
except
end;
finally
end;
end;

posted @ 2020-12-18 21:25  丹心石  阅读(555)  评论(0编辑  收藏  举报