I have a question which I have no idea about (and so I cannot post any code this time) My question is how can I centre text in a batch cmd window, how can I resize a cmd window using script within the batch file, and how can I do the same with the position of the cmd window on the screen. Thanks in advance ;)
-
1I am pretty sure you can not resize a cmd window from batch code, or position it on screen. – user3599730 Jun 15 '14 at 09:38
-
https://onedrive.live.com/redir?resid=E2F0CE17A268A4FA%21121 and look for topmost.zip. The source is also in a zip. – phd443322 Jun 15 '14 at 09:49
2 Answers
Update: Resize and reposition the console, Align & color text
Edit:
- Algorithm to calculate Y and X axis values for console centering corrected to account for the relationship between screen resolution and console size.
- ANSI Escape character now generated within the script
Turns out that with a little bit of tricky work with batch / vbs hybrid the console positioning can be achieved.
Video of the script in action: https://www.youtube.com/watch?v=YlUwZYRmXlo
The below script uses a wmic command processed with a for loop to assign the current screen resolution X and Y axis values to variables, Which are then used to calculate the ( Approximate ) X Y positions required to centre the console.
::: Batch script to reposition console, includes macro to output text Aligned Right, Centre or Left.
::: Script fetches the current screen resolution and calculates the X / Y coordinates needed to position
::: the console window in the centre of the screen.
::: Script updated to allow positioning of console at screen top left with any 4th parameter
::: Note : If called or started from cmd.exe or another batch, this script will end the parent Process.
@Echo Off & CD "%~dp0"
Set "AlignFile=%~dpnx0"
Setlocal DisableDelayedExpansion
(Set LF=^
%= NewLine =%)
Set ^"\n=^^^%LF%%LF%^%LF%%LF%^^"
%= Define console width and values for text alignment =%
Set @Align_Centre=Set /A "%%H=(Console_Width / 2) - (Len / 2)"
Set @Align_Right=Set /A "%%H=(Console_Width - Len)"
Set @Align_Left=Set /A "%%H=0"
%= @Align Macro calculates string length then uses 2nd Parameter to Act on Alignment Calculation =%
%= Macro appends spaces to the string depending on Alignment value / mode chosen to position, then output string to console. =%
Set @Align=for /L %%n in (1 1 2) do if %%n==2 (%\n%
For /F "tokens=1,* delims=, " %%G in ("!argv!") do (%\n%
If not "!%%~G!"=="" (Set "TextOut=!%%~G!") Else (Set "TextOut=%%~G")%\n%
Set LenTrim=Start%\n%
For /L %%a in (1,1,!Console_Width!) Do (%\n%
IF NOT "!LenTrim!"=="" (%\n%
Set LenTrim=!TextOut:~0,-%%a!%\n%
If "!LenTrim!"=="" Set "Len=%%a"%\n%
) %\n%
) %\n%
IF /I "%%H"=="C" %@Align_Centre% %\n%
IF /I "%%H"=="R" %@Align_Right% %\n%
IF /I "%%H"=="L" %@Align_Left% %\n%
For /L %%# in (1,1,!%%H!) Do Set "TextOut= !TextOut!" %\n%
Echo(!Color!!TextOut!!white!^&^& Endlocal %\n%
) %\n%
) ELSE setlocal enableDelayedExpansion ^& set argv=,
REM Color Macro Variables
::: / Creates variable /AE = Ascii-27 escape code.
::: - http://www.dostips.com/forum/viewtopic.php?t=1733
::: - https://stackoverflow.com/a/34923514/12343998
:::
::: - /AE can be used with and without DelayedExpansion.
Setlocal
For /F "tokens=2 delims=#" %%a in ('"prompt #$H#$E# & echo on & for %%b in (1) do rem"') do (
Endlocal
Set "/AE=%%a"
)
::: \
Set "@Color=Call :Color "
Setlocal EnableDelayedExpansion
Set /A Red=31,Green=32,Yellow=33,dark.blue=34,Purple=35,light.Blue=36,White=0,Grey=90,Pink=91,Beige=93,Aqua=94,Magenta=95,Teal=96
For %%A in (Red,Green,Yellow,dark.blue,Purple,light.Blue,White,Grey,Pink,Beige,Aqua,Magenta,Teal) do Call Set "%%A=%/AE%[!%%A!m"
Setlocal DisableDelayedExpansion
Set "@Hold=Call :ColorLetters "Next." & Echo. & Pause>nul"
If Not "%~3"=="" (
Set "AlignFile=%~3"
Set "Console_Width=%~2"
Goto :%~1
) Else (Goto :main)
%= Subroutine to process output of wmic command into usable variables for screen dimensions (resolution) =%
:ChangeConsole <Lines> <Columns> <Label to Resume From> <If a 4th parameter is Defined, Aligns screen at top left>
Setlocal EnableDelayedExpansion
%= Get screen Dimensions =%
For /f "delims=" %%# in ('"wmic path Win32_VideoController get CurrentHorizontalResolution,CurrentVerticalResolution /format:value"') do (
Set "%%#">nul
)
%= Calculation of X axis relative to screen resolution and console size. Resolution scales to Max Columns ~170 =%
Set /A XresScale=CurrentHorizontalResolution / 170
Set /A HorzCentre=CurrentHorizontalResolution / 2
Set /A CentreX= HorzCentre - ( ( %~2 * XresScale ) / 2 )
%= calculation of Y axis relative to screen resolution and console size. Resolution scales to Max Lines ~ 43 =%
Set /A YresScale= CurrentVerticalResolution / 43
Set /A VertCentre=CurrentVerticalResolution / 2
Set /A CentreY= VertCentre - ( ( %~1 * YresScale ) / 2 )
%= Optional 4th parameter can be used to align console at top left of screen instead of screen centre =%
If Not "%~4"=="" (Set /A CentreY=0,CentreX=-8)
%= .Vbs script creation and launch to reopen batch with new console settings, combines with =%
Set "Console_Width=%~2"
%= Creates a batch file to reopen the main script using Call with parameters to define properties for console change and the label to resume from =%
(
Echo.@Mode Con: lines=%~1 cols=%~2
Echo.@Title Res: %CurrentHorizontalResolution%x%CurrentVerticalResolution% X,Y Pos: %CentreX%,%CentreY% Con Size: Cols = %~2 Lines = %~1
Echo.@Call "%AlignFile%" "%~3" "%~2" "%AlignFile%"
)>"%temp%\ChangeConsole.bat"
(
Echo.Set objWMIService = GetObject^("winmgmts:\\.\root\cimv2"^)
Echo.Set objConfig = objWMIService.Get^("Win32_ProcessStartup"^)
Echo.objConfig.SpawnInstance_
Echo.objConfig.X = %CentreX%
Echo.objConfig.Y = %CentreY%
Echo.Set objNewProcess = objWMIService.Get^("Win32_Process"^)
Echo.intReturn = objNewProcess.Create^("%temp%\ChangeConsole.bat", Null, objConfig, intProcessID^)
)>"%temp%\Consolepos.vbs"
%= Starts the companion batch script to Change Console properties, ends the parent =%
Start "" "%temp%\Consolepos.vbs" & Exit
:Color
Setlocal EnableDelayedExpansion
Set "Color=!%~1!"
( Endlocal & Set "Color=%Color%" )
Exit /B
:Colorwords
Setlocal EnableDelayedExpansion
Set #A=31
For %%A in (%*) do (
Set "Word=%%~A"
Call :ColorPrint "!Word!"
<nul set /p=%/AE%[30m.%/AE%[0m
)
Endlocal
Exit /B
:ColorLetters
Setlocal EnableDelayedExpansion
Set #A=31
For %%A in (%*) do (
Set "Word=%%~A"
For %%B In (a b c d e f g h i j k l m n o p q r s t u v w x y z . [ ] ) do Set "Word=!Word:%%~B=%%~B !
Call :ColorPrint "!Word!"
<nul set /p=%/AE%[30m.%/AE%[0m
)
Endlocal
Exit /B
:ColorPrint
For %%C in (%~1) do (
<nul set /p=%/AE%[!#A!m%%~C
Set /A #A+=1
IF "!#A!"=="37" (Set #A=31)
)
Exit /B
:main
%= Remainder of Script examples the usage of Subroutines and macro's =%
%= If a 4rd parameter is used, Console will be positioned at top left of screen =%
Call :ChangeConsole 50 50 Display_Text_1 top
:Display_Text_1
%@Color% red & For %%B in ("Show this" "in centre") do Set "Text=%%~B" & %@Align% Text C
%@hold%
%@Color% green & For %%B in ("Show this" "on right") do Set "Text=%%~B" & %@Align% Text R
%@hold%
%@Color% light.blue & For %%B in ("Show this" "on left") do Set "Text=%%~B" & %@Align% Text L
%@hold%
Call :ChangeConsole 40 150 Display_Text_2
:Display_Text_2
%@Color% pink & Set "string=<< %%A Left String%% \" & %@Align% string L
%@hold%
Call :ChangeConsole 30 175 Display_Text_3
:Display_Text_3
%@Color% teal & Set "string=|^ A Centred String ^|" & %@Align% string C
%@hold%
Call :ChangeConsole 20 30 Display_Text_4
:Display_Text_4
%@Color% magenta & Set "string=/ A !Right String!>>" & %@Align% string R
%@hold%
(taskkill /pid WScript.exe /f /t) >nul 2>nul
Timeout 1 >nul
Del /F "%temp%\Consolepos.vbs" >nul 2>nul
Del /F "%temp%\ChangeConsole.bat" >nul 2>nul
exit /b
Note:
- Script is restarted in order to effect the new console position. This needs to be accounted for by Conditioning script execution so that it doesn't enter an endless loop of restarting the batch file, and also ensuring any variables needed for the scripts continuation are assigned when the script reloads.
- It also means the console cannot be repositioned more than once during the files execution without implementing a system to store, retrieve and act on the scripts previous status, typically by using another file to store the current :label in and testing on execution which label the script should resume from.
- In the example script, this is done using a temporary batch file created in the script to Call the Original batch with Parameters for Console Width and Label to be executed after the Console properties have been changed.
An example with a 4th parameter, for Alignment at top left:
Call :ChangeConsole 45 50 Display_Text_1 top

- 2,747
- 3
- 10
- 25
You can re-size a console in batch
through the use of the mode
command:
MODE CON: COLS=20 LINES=30
For more info type mode /?
.
You could probably write a script to do this for you but the manual way to do this once you have re-sized the windows would be:
Main.bat
set /a h=30
set /a w=20
set msg=Hello World
set /a msglen=11
Mode Con: Cols=%w% Lines=%h%
Print.bat %w% %h% "%msg% %msglen%
Print.bat
@echo off
cls
for /l %%a in (1, 1, %2 / 2 - 1) do (Echo.)
for /l %%b in (1, 1, %1 / 2 - %4) do (<nul set /p"= ")
:: In the above "%4" is the length of the string
Echo %3
Echo.
And that SHOULD print out Hello World in the middle of the screen. (I haven't checked it though so tell me if there are any problems)
Mona
-
Re-positioning is not possible(atleast not in batch), but you can choose to have the window minimized or maximized. – Monacraft Jun 15 '14 at 11:37
-
repositioning is possible within batch, with a little batch made vbs shenanigans. – T3RR0R Apr 08 '20 at 07:43