如何处理从我的GUI应用程序启动的控制台窗口?

时间:2012-12-10 06:30:24

标签: delphi winapi windows-7 delphi-xe2

在我的GUI应用程序中,我运行控制台应用程序并需要其窗口的句柄。我尝试使用EnumWindows(),请参阅下面的代码,但它不起作用。在列表中没有我的控制台应用程序。

type
  TEnumWindowsData = record
    ProcessId: Cardinal;
    WinHandle: THandle;
    List: TStrings;                 // For test only
  end;
  PEnumWindowsData = ^TEnumWindowsData;

function FindWindow(hWnd: THandle; lParam: LPARAM): BOOL; stdcall;
var
  ParamData: TEnumWindowsData;
  ProcessId: Cardinal;
  WinTitle: array[0..200] of Char;  // For test only
begin
  ParamData := PEnumWindowsData(lParam)^;
  GetWindowThreadProcessId(hWnd, ProcessId);
  if ProcessId <> ParamData.ProcessId then
    Result := True
  else begin
    ParamData.WinHandle := hWnd;
    Result := False;
  end;
  // For test only
  GetWindowText(hWnd, WinTitle, Length(WinTitle) - 1);
  ParamData.List.Add(IntToStr(ProcessId) + ' ' + IntToStr(hWnd) + ' ' + WinTitle);
end;

procedure TForm1.Button1Click(Sender: TObject);

  function RunApp(const AProgram: string): Cardinal;
  var
    StartupInfo: TStartupInfo;
    ProcessInformation: TProcessInformation;
  begin
    Result := 0;
    ...
    if CreateProcess(nil, PChar(AProgram), nil, nil, False,
          NORMAL_PRIORITY_CLASS, nil, nil, StartupInfo, ProcessInformation)
    then
      Result := ProcessInformation.dwProcessId;
    ...
  end;

var
  ParamData: TEnumWindowsData;
begin
  ParamData.ProcessId := RunApp('cmd.exe /C D:\TMP\TEST.exe');
  ParamData.WinHandle := 0;
  ParamData.List := Memo1.Lines;
  EnumWindows(@FindWindow, THandle(@ParamData));

  FWindowHandle := ParamData.WinHandle;
end;

2 个答案:

答案 0 :(得分:10)

以下代码只是创建进程(控制台应用程序),通过AttachConsole函数将您的进程附加到新创建的控制台,并从该连接的控制台使用GetConsoleWindow函数获取窗口句柄。

以下代码的最大弱点是CreateProcess函数在此时立即返回,当控制台尚未完全初始化时,以及当您尝试立即连接控制台时,您将失败。不幸的是,没有WaitForInputIdle函数for console applications所以作为一种可能的解决方法,我会选择尝试在一些有限的循环计数中附加控制台,一旦成功,获取句柄并分离控制台。

在代码中可能如下所示。那里的RunApp函数应该返回控制台窗口的句柄(假设你只从它运行控制台应用程序),并且应该等待大约。对于控制台应用程序,您已经开始可以连接1秒钟了。您可以通过更改Attempt变量的初始值和/或更改Sleep间隔来修改此值。

function GetConsoleWindow: HWND; stdcall;
  external kernel32 name 'GetConsoleWindow';
function AttachConsole(dwProcessId: DWORD): BOOL; stdcall;
  external kernel32 name 'AttachConsole';

function RunApp(const ACmdLine: string): HWND;
var
  CmdLine: string;
  Attempt: Integer;
  StartupInfo: TStartupInfo;
  ProcessInfo: TProcessInformation;
begin
  Result := 0;
  FillChar(StartupInfo, SizeOf(TStartupInfo), 0);
  FillChar(ProcessInfo, SizeOf(TProcessInformation), 0);
  StartupInfo.cb := SizeOf(TStartupInfo);
  StartupInfo.dwFlags := STARTF_USESHOWWINDOW;
  StartupInfo.wShowWindow := SW_SHOWNORMAL;
  CmdLine := ACmdLine;
  UniqueString(CmdLine);
  if CreateProcess(nil, PChar(CmdLine), nil, nil, False,
    CREATE_NEW_CONSOLE, nil, nil, StartupInfo, ProcessInfo) then
  begin
    Attempt := 100;
    while (Attempt > 0) do
    begin
      if AttachConsole(ProcessInfo.dwProcessId) then
      begin
        Result := GetConsoleWindow;
        FreeConsole;
        Break;
      end;
      Sleep(10);
      Dec(Attempt);
    end;
    CloseHandle(ProcessInfo.hThread);
    CloseHandle(ProcessInfo.hProcess);
  end;
end;

然后你可以,例如以这种方式更改您的lauched应​​用程序的控制台窗口的标题:

procedure TForm1.Button1Click(Sender: TObject);
var
  S: string;
  ConsoleHandle: HWND;
begin
  ConsoleHandle := RunApp('cmd.exe');
  if ConsoleHandle <> 0 then
  begin
    S := 'Hello! I''m your console, how can I serve ?';
    SendTextMessage(ConsoleHandle, WM_SETTEXT, 0, S);
  end;
end;

答案 1 :(得分:5)

创建控制台进程

- 找到流程窗口

找到控制台窗口的设置标题

- 写入找到的控制台

unit Unit3;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
  TForm1 = class(TForm)
    Button1: TButton;
    Button2: TButton;
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
  private
    PID: DWORD;
  public
    { Public-Deklarationen }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
var
  AProgram: String;
  StartupInfo: TStartupInfoW;
  ProcessInfo: TProcessInformation;
begin
  AProgram := 'cmd /K Dir C:\temp';   // using /K for keeping console alive
  UniqueString(AProgram);             // ensure that AProgram is writeable by API
  ZeroMemory(@StartupInfo, SizeOf(StartupInfo)); // create minimum startup info
  StartupInfo.cb := SizeOf(StartupInfo);
  StartupInfo.dwFlags := STARTF_USESHOWWINDOW;
  StartupInfo.wShowWindow := SW_SHOW;
  if CreateProcess(nil, PChar(AProgram), nil, nil, False,  // Create Consoleprocess
    CREATE_NEW_CONSOLE or NORMAL_PRIORITY_CLASS, nil, nil, StartupInfo,
    ProcessInfo) then
    try
      PID := ProcessInfo.dwProcessId;  // Store  ProcessId to PID
    finally
      // close not longer required handles
      Showmessage(IntToStr(Integer(CloseHandle(ProcessInfo.hProcess))));
      Showmessage(IntToStr(Integer(CloseHandle(ProcessInfo.hThread))));
    end;
end;

type
  PEnumInfo = ^TEnumInfo;
  TEnumInfo = record ProcessID: DWORD; HWND: THandle; end;

function EnumWindowsProc(Wnd: DWORD; var EI: TEnumInfo): BOOL; stdcall;
var
  PID: DWORD;
begin
  GetWindowThreadProcessID(Wnd, @PID);  // get processID from WND of Enumeration
  // continue EnumWindowsProc if found PID is not our wished, visible and enabled  processID (EI.ProcessID)
  Result := (PID <> EI.ProcessID) or (not IsWindowVisible(WND)) or
    (not IsWindowEnabled(WND));
  if not Result then // WND found for EI.ProcessID
    EI.HWND := WND;
end;

function FindMainWindow(PID: DWORD): DWORD;
var
  EI: TEnumInfo;
begin
  //Store our processID and invalid Windowhandle to EI
  EI.ProcessID := PID;
  EI.HWND := 0;
  EnumWindows(@EnumWindowsProc, Integer(@EI));
  Result := EI.HWND;
end;

function AttachConsole(dwProcessId: DWORD): BOOL; stdcall;
  external kernel32 name 'AttachConsole';

procedure TForm1.Button2Click(Sender: TObject);
var
  Wnd: HWND;
  S: String;
begin
  if PID <> 0 then  // do we have a valid ProcessID
  begin
    Wnd := FindMainWindow(PID);
    if Wnd <> 0 then  // did we find the window handle
    begin
      S := 'Test';
      // change caption of found window
      SendMessage(Wnd, WM_SETTEXT, 0, LPARAM(@S[1]));
      if AttachConsole(PID) then   // are we able to attach to console of our proecess?
      begin
        Writeln('Here we are'); // write to attached console
        FreeConsole;  // free if not longer needed
      end;
    end;
  end;
end;

end.