Advertisement
T3RRYT3RR0R

Template for advanced batch programs

Apr 22nd, 2020
1,093
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Batch 12.99 KB | None | 0 0
  1. ::: ** A template for batch scripts to allow control over display properties and the playing of sound files. ** /
  2. :::
  3. ::: Features:
  4. ::: - Support for automatically centering the console on screen, or positioning the console screen top left.
  5. :::   - calculates centre position relative to console size and screen resolution. (mode 1000 not supported)
  6. :::
  7. ::: - Supports a variety of options for displaying text in the console including:
  8. :::  - Aligning text Left, Centre or Right within the console in the chosen color
  9. :::  - Outputing text in multiple colors on the same line - even within the same word.
  10. :::
  11. ::: - Can play any music or sound file compatable with windows media player
  12. :::  - Volume range of 0-100
  13. :::  - Single play or Looping of Sounds
  14. :::
  15. ::: - No extra windows are visible during the use of the vbs or bat programs used to play, monitor or stop the music.
  16. :::  - Automaticaly stops all vbs scripts when no cmd.exe windows are open
  17. :::
  18. ::: - Subroutines limited to single use code elements wherever possible
  19. ::: - Macro's used for code elements that will be heavily reused for faster performance
  20. ::: \
  21.  
  22. ::: ** Note: Pastebin does note display all lines of this code correctly.
  23. ::: - you'll need to either copy it from the raw paste data, or download the file.
  24.  
  25. %= This remark style is reserved for use within macro definition as it does not disrupt the definition =%
  26.  
  27. @ECHO OFF
  28.  
  29. ::: / Program must be stored in a folder with read / write access. change directory to this programs folder
  30.     CD "%~dp0"
  31. ::: \
  32.  
  33. ::: / Define pathways and create subfolders used for self generated component files
  34. ::: - calls subroutines to create component files if they do not already exist
  35.     Set "ProgDir=%~dp0"
  36.     If not exist "%ProgDir%Sounds" MD "%ProgDir%Sounds"
  37.     Set "Sounds=%ProgDir%Sounds"
  38.     Set "Player=%Sounds%\BatchMusicPlayer.bat"
  39.     Set "MusicStopper=%Sounds%\StopMusic.bat"
  40.     Set "Monitor=%Sounds%\BatchMonitor.vbs"
  41.     If not Exist "%Player%" Call :makeplayer
  42.     If not Exist "%MusicStopper%" Call :makestopper
  43.     If not Exist "%Monitor%" Call :makemonitor
  44. ::: \
  45.  
  46. ::: / Creates variable /AE = Ascii-27 escape code, used to change text color.
  47. ::: - http://www.dostips.com/forum/viewtopic.php?t=1733
  48. ::: - https://stackoverflow.com/a/34923514/12343998
  49. :::
  50. ::: - /AE can be used  with and without DelayedExpansion.
  51.     Setlocal
  52.     For /F "tokens=2 delims=#" %%a in ('"prompt #$H#$E# & echo on & for %%b in (1) do rem"') do (
  53.         Endlocal
  54.         Set "/AE=%%a"
  55.     )
  56. ::: \
  57.  
  58. ::: / Assigns this Batch's home path to a variable for use in recalling itself after positioning the console
  59.     Set "ThisProgram=%~dpnx0"
  60. ::: \
  61.  
  62.     Setlocal DisableDelayedExpansion
  63.  
  64.     (Set LF=^
  65.  
  66.  
  67.     %= NewLine =%)
  68.  
  69.     Set ^"\n=^^^%LF%%LF%^%LF%%LF%^^"
  70.  
  71. ::: / mini-Macro to Pseudo pipe complex strings into Macros.
  72.     Set "Params|=Set Args-In="
  73. ::: \
  74.  
  75. ::: / Macro for safely taking user input for assignment to variables.
  76.     Set @Input=^&for /L %%n in (1 1 2) do if %%n==2 (%\n%
  77.         for /F "tokens=1,2,3 delims=, " %%G in ("!argv!") do (%\n%
  78. %= Assign default value for variable =%
  79.         Set "%%G=%%I"%\n%
  80. %= Give user 3 opportunities to provide their own value before default is finalised =%
  81.         For %%a in (!Args-In!) do For /L %%C in (1,1,3) do If "!%%~G!" == "%%~I" Set /P "%%~G=!%%H!%%~a!Off!"%\n%
  82.         ) %\n%
  83.     ) ELSE set argv=,
  84. ::: \
  85.  
  86. ::: - Calculate console width and values for MSG alignment for the Align macro
  87.  
  88.     Set @Align_Centre=Set /A "%%G=(Console_Width / 2) - (Len / 2)"
  89.     Set @Align_Right=Set /A "%%G=(Console_Width - Len)"
  90.     Set @Align_Left=Set /A "%%G=0"
  91.  
  92. ::: / @Align Macro calculates string length then uses 2nd Parameter to Act on Alignment Calculation
  93. ::: - Macro appends spaces to the string depending on Alignment value / mode chosen to position, then output string to console
  94.  
  95.     Set @Align=^&for /L %%n in (1 1 2) do if %%n==2 (%\n%
  96.         For /F "tokens=1,* delims=, " %%G in ("!argv!") do (%\n%
  97.             Set "MSGOut=!Args-In!"%\n%
  98.             Set LenTrim=Start%\n%
  99.             For /L %%a in (1,1,!Console_Width!) Do (%\n%
  100.                 IF NOT "!LenTrim!"=="" (%\n%
  101.                     Set LenTrim=!MSGOut:~0,-%%a!%\n%
  102.                     If "!LenTrim!"=="" Set "Len=%%a"%\n%
  103.                 ) %\n%
  104.             ) %\n%
  105.             IF /I "%%G"=="C" %@Align_Centre% %\n%
  106.             IF /I "%%G"=="R" %@Align_Right% %\n%
  107.             IF /I "%%G"=="L" %@Align_Left% %\n%
  108.             For /L %%# in (1,1,!%%G!) Do Set "MSGOut= !MSGOut!" %\n%
  109.             Echo(!Color!!MSGOut!!white!^&^& Endlocal %\n%
  110.         ) %\n%
  111.     ) ELSE setlocal enableDelayedExpansion ^& set argv=,
  112. ::: \
  113.  
  114. ::: / custom pause prompt macro that accepts long strings as input when paired with the Param macro
  115.     Set @Hold=^&for /L %%n in (1 1 2) do if %%n==2 (%\n%
  116.         For /F "tokens=1 delims=, " %%G in ("!argv!") do (%\n%
  117.         (For %%A in (!Args-In!) Do Call :Color%%~G "%%~A") ^& Echo.!Off! ^& Pause^>nul%\n%
  118.         ) %\n%
  119.     ) ELSE set argv=,
  120. ::: \
  121.  
  122. ::: * / Color Macro Variables
  123. :::/ 'Color Change'
  124.     Set "@CC=Set Color="
  125. ::: \
  126.  
  127. ::: / Color code assignment
  128.     Setlocal EnableDelayedExpansion
  129.     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,Off=0,Black=30
  130.     For %%A in (Red,Green,Yellow,dark.blue,Purple,light.Blue,White,Grey,Pink,Beige,Aqua,Magenta,Teal,Off,Black) do Call Set "%%A=%/AE%[!%%A!m"
  131.     Setlocal DisableDelayedExpansion
  132. ::: \
  133. ::: * \
  134.  
  135. ::: / Detects when this program has been restarted after resizing / repositioning the console and restores
  136. ::: - required variables before continuing from the specified label
  137.     If Not "%~3"=="" (
  138.         Set "Console_Width=%~2"
  139.         Set "Console_Hieght=%~3"
  140.         Set "ThisProgram=%~4"
  141.         Goto :%~1
  142.     ) Else (Goto :ConsolePROPS)
  143. ::: \
  144.  
  145. :::: **** Subroutines /
  146.  
  147. ::: * / Subroutine to process output of wmic command into usable variables  for screen dimensions (resolution)
  148.  
  149.     :ChangeConsole <Lines> <Columns> <Label to Resume From> <If a 4th parameter is Defined, Aligns screen at top left>
  150.     Setlocal EnableDelayedExpansion
  151. ::: - Get screen Dimensions
  152.     For /f "delims=" %%# in  ('"wmic path Win32_VideoController  get CurrentHorizontalResolution,CurrentVerticalResolution /format:value"') do (
  153.         Set "%%#">nul
  154.     )
  155.  
  156. ::: - Calculation of X axis relative to screen resolution and console size. Resolution scales to Max Columns ~ 165
  157.     Set /A XresScale=CurrentHorizontalResolution / 165
  158.     Set /A HorzCentre=CurrentHorizontalResolution / 2
  159.     Set /A CentreX= ( HorzCentre - ( ( %~2 * XresScale ) / 2 ) ) - 8
  160. ::: - Calculation of Y axis relative to screen resolution and console size. Resolution scales to Max Lines ~ 43
  161.     Set /A YresScale= CurrentVerticalResolution / 43
  162.     Set /A VertCentre=CurrentVerticalResolution / 2
  163.     Set /A CentreY= VertCentre - ( ( %~1 * YresScale ) / 2 )
  164.  
  165. ::: - Optional 4th parameter can be used to align console at top left of screen instead of screen centre
  166.     If Not "%~4"=="" (Set /A CentreY=0,CentreX=-8)
  167.  
  168. ::: - .Vbs script creation and launch to reopen batch with new console settings, combines with
  169.     Set "Console_Width=%~2"
  170.  
  171. ::: / Creates a batch file to reopen the ConsolePROPS script using Call with parameters to define properties for console
  172. ::: - change and the label to resume from.
  173.         (
  174.         Echo.@Mode Con: lines=%~1 cols=%~2
  175.         Echo.@Title Res: %CurrentHorizontalResolution%x%CurrentVerticalResolution% X,Y Pos: %CentreX%,%CentreY% Con Size: Cols = %~2 Lines = %~1
  176.         Echo.@Call "%ThisProgram%" "%~3" "%~2" "%~1" "%ThisProgram%"
  177.         )>"%temp%\ChangeConsole.bat"
  178. ::: \
  179.  
  180. ::: / Vbs used to position the console, and open the above companion file used to reload this program
  181.         (
  182.         Echo.Set objWMIService = GetObject^("winmgmts:\\.\root\cimv2"^)
  183.         Echo.Set objConfig = objWMIService.Get^("Win32_ProcessStartup"^)
  184.         Echo.objConfig.SpawnInstance_
  185.         Echo.objConfig.X = %CentreX%
  186.         Echo.objConfig.Y = %CentreY%
  187.         Echo.Set objNewProcess = objWMIService.Get^("Win32_Process"^)
  188.         Echo.intReturn = objNewProcess.Create^("%temp%\ChangeConsole.bat", Null, objConfig, intProcessID^)
  189.         )>"%temp%\Consolepos.vbs"
  190.  
  191. %= Starts the companion batch script to Change Console properties, ends the parent =%
  192.     Start "" "%temp%\Consolepos.vbs" & Exit
  193. ::: * \
  194.  
  195. :Colorwords
  196.     Setlocal EnableDelayedExpansion
  197.     IF "!#A!" == "" Set "#A=31"
  198.     For %%A in (%*) do (
  199.         Set "Word=%%~A"
  200.         Call :ColorPrint "!Word!"
  201.         <nul set /p=%/AE%[30m.%/AE%[0m
  202.     )
  203.     Endlocal
  204. Exit /B
  205.  
  206. :ColorLetters
  207.     Setlocal EnableDelayedExpansion
  208.     IF "!#A!" == "" Set "#A=31"
  209.     For %%A in (%*) do (
  210.         Set "Word=%%~A"
  211.         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 !
  212.         Call :ColorPrint "!Word!"
  213.         <nul set /p=%/AE%[30m.%/AE%[0m
  214.     )
  215.     Endlocal
  216. Exit /B
  217.  
  218. :ColorPrint
  219. IF "!#A!" == "" Set #A=31
  220. For %%C in (%~1) do (
  221.     <nul set /p=%/AE%[!#A!m%%~C
  222.     Set /A #A+=1
  223.     IF "!#A!"=="37" (Set #A=31)
  224. )
  225. Exit /B
  226.  
  227.  
  228. ::: / creates a companion batch file thats called with arguments for trackpath, volume and loop tf values
  229. :makeplayer
  230.     (
  231.     Echo.@ECHO OFF
  232.     Echo.Set "MusicPath=%%~1"
  233.     Echo.Set "vol=%%~2"
  234.     Echo.Set "Loop_TF=%%~3"
  235. ::: - Change to the Directory you want to create the Music Launcher in.
  236.     Echo.PUSHD %%sounds%%
  237. ::: - Ensure no Conflict with the Previous Script.
  238.     Echo.IF exist PlayMusic.vbs ^(
  239.     Echo.DEL PlayMusic.vbs
  240.     Echo.^)
  241. ::: - Creates a vbs Script to Launch the music (Occurs without any visual indication or prompting)
  242.     Echo.^( echo Set Sound = CreateObject^("WMPlayer.OCX.7"^^^)
  243.     Echo.echo Sound.URL = "%%MusicPath%%"
  244.     Echo.echo Sound.settings.volume = %%vol%%
  245.     Echo.echo Sound.settings.setMode "loop", %%Loop_TF%%
  246.     Echo.echo Sound.Controls.play
  247.     Echo.echo While Sound.playState ^^^<^^^> 1
  248.     Echo.echo      WScript.Sleep 100
  249.     Echo.echo Wend
  250.     Echo.^)^>PlayMusic.vbs
  251.     Echo.start /min PlayMusic.vbs
  252. ::: -   Return to the Previous Directory
  253.     Echo.POPD
  254. ::: -   Exit the Launcher and return to Previous batch program.
  255.     Echo.Goto :EOF
  256.     )>"%Player%"
  257. Exit /B
  258. ::: \
  259.  
  260. ::: / Monitor checks process status of cmd.exe every 1500 ms and calls StopMusic batch file to taskill all vbs scripts when
  261. ::: - cmd.exe process count is 0. Delay is to reduce CPU usage of the WMI service
  262. :makemonitor
  263.     (
  264.     ECHO Set objWMIService = GetObject ("winmgmts:"^)
  265.     ECHO Set proc = objWMIService.ExecQuery("select * from Win32_Process Where Name='cmd.exe'"^)
  266.     ECHO DO while proc.count ^> 0
  267.     ECHO Set proc = objWMIService.ExecQuery("select * from Win32_Process Where Name='cmd.exe'"^)
  268.     ECHO if proc.count ^< 1 then exit do
  269.     ECHO wscript.sleep 1500
  270.     ECHO loop
  271.     ECHO Set WshShell=createobject("wscript.shell"^)
  272.     ECHO WshShell.run "%MusicStopper%", 0, true
  273.     )>"%Monitor%"
  274. Exit /B
  275. ::: \
  276.  
  277. ::: / Simple taskkill script to terminate vbs scripts on program exit
  278. :makestopper
  279.     (
  280.     Echo.@ECHO OFF
  281.     Echo.taskkill /pid WScript.exe /f /t ^>nul
  282.     Echo.Goto :EOF
  283.     )>"%MusicStopper%"
  284. Exit /B
  285. ::: \
  286.  
  287. ::: **** End of Subroutines \
  288.  
  289.  
  290. :ConsolePROPS
  291.  
  292. ::: / Call subroutine with desired console properties.
  293. ::: - Param 1: Lines (Y Axis)
  294. ::: - Param 2: Columns (X Axis)
  295. ::: - Param 3: Label Name to resume from
  296. ::: - Param 4: Optional. Aligns console at top left of screen instead of screen Centre (any 4th parameter will do this)
  297.  
  298.     Call :ChangeConsole 38 120 Main
  299.  
  300. ::: / **** MAIN script body of your program goes below. **** \ :::
  301. :Main
  302.  
  303. ::: / Delayed expansion required for the expansion of script within Macro variables
  304.     Setlocal EnableDelayedExpansion
  305. ::: \
  306.  
  307. ::: / Begins vbs monitor to call the taskkill script and end all vbs's once cmd.exe is closed.
  308. ::: - Must be started after resizing / aligning console
  309. ::: - Should be started before calling upon the music player
  310.     Start "" "%Monitor%"
  311. ::: \
  312.     %@CC%!red!& For %%B in ("Right aligned" "text display example") do %!!|%%%~B%@Align% R
  313.     %@CC%!magenta!& %!!|%left aligned text%@Align% L
  314.     %@CC%!light.blue!& %!!|%Centre aligned text.%@Align% C
  315.  
  316. ::: / Music player call example
  317. ::: - volume must be an integer between 0 and 100
  318.     Set "vol=100"
  319. ::: - loop value must be 'true' or 'false'
  320.     Set "Loop_TF=true"
  321. ::: - a full and valid track path needs to be assigned to the variable in order to use the music player
  322.     Set "track="
  323.  
  324. ::: / Example usage of custom prompt for user input to variables. Doubleqouting of Params required for special Characters.
  325. ::: - If no input is given, the 3rd Arg, %~d0\Windows\Media\Ring01.wav will be set to the example track variable as a default
  326. ::: - %~d0\ assumes the windows directory and this batch share the same drive, without assuming it's on the C: drive.
  327.     %!!|%"Enter a path for your song %yellow%:>"%@Input% track green %~d0\Windows\Media\Ring01.wav
  328.     %@CC%!teal!& For %%B in ("You entered:" "%track%") do %!!|%%%~B%@Align% C
  329. ::: \
  330.  
  331. ::: - Calls the music player with the desired sound, volume and repeat state if all variables set
  332. ::: - If conditions used to deactivate the call until a track path is provided.
  333.  
  334. IF NOT "%track%" == "" (
  335.     If Exist "%track%" (
  336.         CALL "%player%" "!track!" !vol! !Loop_TF!
  337.     ) Else ( %@CC%!red!& %!!|%No file at that filepath%@Align% C )
  338. ) Else (
  339.     %@CC%!red!& %!!|%No track selected%@Align% C
  340. )
  341. ::: \
  342.  
  343.  
  344.  
  345. ::: / Example of a custom pause prompt. 'letters' or 'words' are valid for Arg 1.
  346.     %!!|%Example of a custom pause - The song [or ringing] will close next.%@hold% letters
  347. ::: \
  348.  
  349. :end
  350. exit
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement