2015年11月2日 星期一

delphi console dos command 螢幕 鍵盤 轉向 擷取 輸出


  WinExec('xcopy c\:old.txt c\:newfilewithlongname.txt', SW_SHOWNORMAL)

http://fixedbycode.blogspot.tw/2014/07/redirecting-or-capturing-output-from.html
Redirecting??
Redirecting or capturing output from processes

find windows

把某個視窗(程式)的容器指定給自己的視窗
var
  H: HWND;
begin
  H := FindWindow('ConsoleWindowClass', 'C:\Windows\system32\cmd.exe');
  if H<>0 then
  begin
    WinApi.Windows.SetParent(H, Memo1.Handle);
    SetWindowPos(H, 0, 0, 0, ClientWidth, ClientHeight, SWP_ASYNCWINDOWPOS);
  end;

Redirecting STDIN, STDOUT and STDERR from a process created/started 

這有用到 “泛型 ” 是 抓取 螢幕 輸出 內容
procedure TForm1.CaptureConsoleOutput(const cmd, param: String; CallBackProc:
  TArg);
const
  secAttr: TSecurityAttributes = (
    nLength: SizeOf(TSecurityAttributes);
    bInheritHandle: True);
  bufSize = 2400;
var
  rPipe: THandle;
  wPipe: THandle;
  suiRec: TStartupInfo;
  piRec: TProcessInformation;
  dRun, dAvail, dRead: DWORD;
  rBuf: array [0..bufSize] of AnsiChar;
begin
  if CreatePipe(rPipe, wPipe, @secAttr, 0) then
  try
    FillChar(suiRec, SizeOf(TStartupInfo), #0);
    suiRec.cb := SizeOf(TStartupInfo);
    suiRec.dwFlags := STARTF_USESTDHANDLES or STARTF_USESHOWWINDOW;
    suiRec.wShowWindow := SW_HIDE;
    suiRec.hStdInput := rPipe;
    suiRec.hStdOutput := wPipe;
    suiRec.hStdError := wPipe;
    if CreateProcess(nil, PChar(cmd+' '+param), @secAttr, @secAttr, True,
      NORMAL_PRIORITY_CLASS, nil, nil, suiRec, piRec) then
    try
      repeat
        dRun := WaitForSingleObject(piRec.hProcess, 100);
        PeekNamedPipe(rPipe, nil, 0, nil, @dAvail, nil);
        if (dAvail > 0) then
        repeat
          dRead := 0;
          ReadFile(rPipe, rBuf[0], bufSize, dRead, nil);
          rBuf[dRead] := #0;
          OemToCharA(rBuf, rBuf);
          CallBackProc(rBuf);
        until (dRead < bufSize);
        Application.ProcessMessages;
      until (dRun <> WAIT_TIMEOUT);
    finally
      CloseHandle(piRec.hProcess);
      CloseHandle(piRec.hThread);
    end;
  finally
    CloseHandle(rPipe);
    CloseHandle(wPipe);
  end;
end;



沒有留言: