批处理 - 居中、调整大小和重新定位 [英] Batch - Centre, Resize and Reposition

查看:88
本文介绍了批处理 - 居中、调整大小和重新定位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个我不知道的问题(所以这次我不能发布任何代码)我的问题是如何在批处理 cmd 窗口中居中文本,如何使用批处理文件中的脚本调整 cmd 窗口的大小,以及如何对 cmd 窗口在屏幕上的位置执行相同操作.提前致谢;)

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 ;)

推荐答案

更新:调整控制台的大小和位置,对齐 &彩色文字

  • 计算控制台居中 Y 轴和 X 轴值的算法已更正以考虑屏幕分辨率和控制台尺寸之间的关系.
  • ANSI 转义字符现在在脚本中生成

事实证明,通过批处理/vbs 混合的一些棘手工作,可以实现控制台定位.

Turns out that with a little bit of tricky work with batch / vbs hybrid the console positioning can be achieved.

正在运行的脚本视频:https://www.youtube.com/watch?v=YlUwZYRmXlo

以下脚本使用通过 for 循环处理的 wmic 命令将当前屏幕分辨率 X 和 Y 轴值分配给变量,然后用于计算使控制台居中所需的(近似)XY 位置.

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

注意:

  • 重新启动脚本以影响新的控制台位置.这需要通过 Conditioning 脚本执行来解决,以便它不会进入重新启动批处理文件的无限循环,并确保在脚本重新加载时分配脚本继续所需的任何变量.
  • 这也意味着在文件执行期间控制台不能被多次重新定位,而无需实现一个系统来存储、检索脚本先前的状态并对其采取行动,通常是通过使用另一个文件来存储当前的 :label 并在执行时进行测试脚本应该从哪个标签恢复.
    • 在示例脚本中,这是使用在脚本中创建的临时批处理文件来完成的,以调用带有控制台宽度和标签参数的原始批处理,以便在控制台属性更改后执行.

    带有第 4 个参数的示例,用于左上角的对齐:

    An example with a 4th parameter, for Alignment at top left:

    调用 :ChangeConsole 45 50 Display_Text_1 top

    这篇关于批处理 - 居中、调整大小和重新定位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆