在我的Win32 VCL应用程序中,我使用ShellExecute启动了许多较小的Delphi控制台应用程序。有没有办法控制那些控制台窗口的位置?我想以屏幕为中心启动它们。
答案 0 :(得分:17)
您可以使用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;
答案 1 :(得分:11)
如果您可以控制控制台应用程序,您可以从控制台应用程序本身内部设置控制台窗口位置:
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.
如果您无法重新编译控制台应用程序,则可以使用FindWindow('ConsoleWindowClass', '<path to the executable>')
获取控制台窗口句柄(如果通过SetConsoleTitle
设置,则Title参数可能会有所不同)。
这种方法的缺点是可以看到控制台窗口&#34;跳跃&#34;从它的默认位置到它的新位置(使用Windows XP测试)。