批量 - 中心,调整大小和重新定位

时间:2014-06-15 09:35:09

标签: windows batch-file

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

2 个答案:

答案 0 :(得分:2)

更新:调整控制台的大小和位置,对齐文本并为文本着色

编辑:

  • 用于计算控制台中心的Y和X轴值的算法已更正,以解决屏幕分辨率和控制台尺寸之间的关系。
  • 现在,在脚本中生成了
  • ANSI Escape字符

事实证明,使用批处理/ vbs混合进行一些棘手的工作即可实现控制台定位。

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

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

::: 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

注意:

  • 脚本重新启动以影响新的控制台位置。这需要通过条件脚本执行来解决,以免进入重新启动批处理文件的无休止循环,并且还确保在脚本重新加载时分配了脚本继续所需的任何变量。
  • 这也意味着在文件执行过程中,如果没有实现一个系统来存储,检索脚本以及对脚本的先前状态进行操作,控制台通常不能被重新定位一次,通常是通过使用另一个文件来存储当前的:label并在执行时进行测试脚本应从哪个标签恢复。
    • 在示例脚本中,这是使用在脚本中创建的临时批处理文件来完成的,以在更改控制台属性后执行具有控制台宽度和标签参数的原始批处理。

第四个参数的示例,用于左上方的Alignment:

Call :ChangeConsole 45 50 Display_Text_1 top

Batch Console Mastery

答案 1 :(得分:1)

您可以使用batch命令在mode中调整控制台的大小:

MODE CON: COLS=20 LINES=30

有关详细信息,请输入mode /?

您可以编写一个脚本来为您执行此操作,但是在重新调整窗口大小后手动执行此操作的方法是:

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.

那应该在屏幕中间打印出Hello World。 (我没有检查过,所以告诉我是否有任何问题)

莫纳