12

在我的 Win32 VCL 应用程序中,我使用 ShellExecute 来启动一些较小的 Delphi 控制台应用程序。有没有办法控制这些控制台窗口的位置?我想以屏幕为中心启动它们。

4

2 回答 2

19

您可以在其结构参数中使用CreateProcess和指定窗口大小和位置。STARTUPINFO在下面的示例函数中,您可以指定控制台窗口的大小,然后根据指定的大小以当前桌面为中心。如果成功,函数返回进程句柄,否则返回 0:

function RunConsoleApplication(const ACommandLine: string; AWidth,
  AHeight: Integer): THandle;
var
  CommandLine: string;
  StartupInfo: TStartupInfo;
  ProcessInformation: TProcessInformation;
begin
  Result := 0;
  FillChar(StartupInfo, SizeOf(TStartupInfo), 0);
  FillChar(ProcessInformation, SizeOf(TProcessInformation), 0);
  StartupInfo.cb := SizeOf(TStartupInfo);
  StartupInfo.dwFlags := STARTF_USESHOWWINDOW or STARTF_USEPOSITION or 
    STARTF_USESIZE;
  StartupInfo.wShowWindow := SW_SHOWNORMAL;
  StartupInfo.dwXSize := AWidth;
  StartupInfo.dwYSize := AHeight;
  StartupInfo.dwX := (Screen.DesktopWidth - StartupInfo.dwXSize) div 2;
  StartupInfo.dwY := (Screen.DesktopHeight - StartupInfo.dwYSize) div 2;
  CommandLine := ACommandLine;
  UniqueString(CommandLine);
  if CreateProcess(nil, PChar(CommandLine), nil, nil, False,
    NORMAL_PRIORITY_CLASS, nil, nil, StartupInfo, ProcessInformation)
  then
    Result := ProcessInformation.hProcess;
end;
于 2012-08-27T10:13:27.967 回答
12

If you have control over the console application, You could set the console window position from inside the console application itself:

program Project1;
{$APPTYPE CONSOLE}
uses
  Windows,
  MultiMon;

function GetConsoleWindow: HWND; stdcall; external kernel32 name 'GetConsoleWindow';

procedure SetConsoleWindowPosition;
var
  ConsoleHwnd: HWND;
  R: TRect;
begin
  ConsoleHwnd := GetConsoleWindow;
  // Center the console window
  GetWindowRect(ConsoleHwnd, R);
  SetWindowPos(ConsoleHwnd, 0,
    (GetSystemMetrics(SM_CXVIRTUALSCREEN) - (R.Right - R.Left)) div 2,
    (GetSystemMetrics(SM_CYVIRTUALSCREEN) - (R.Bottom - R.Top)) div 2,
    0, 0, SWP_NOSIZE);
end;

begin
  SetConsoleWindowPosition;  
  // Other code...
  Readln;
end.

If you can't recompile the console application, you could use FindWindow('ConsoleWindowClass', '<path to the executable>') to obtain the console window handle (the Title parameter could vary if it was set via SetConsoleTitle). The downside with this approach, is that the console window is seen "jumping" from it's default position to it's new position (tested with Windows XP).

于 2012-08-27T09:52:19.247 回答