Search code examples
batch-file

How to move the cursor to the very beginning of the console window in Batch?


I saw someone overwriting a line without the use of CLS by using !CR! (carriage return character):

@echo off
setlocal EnableDelayedExpansion
for /f %%a in ('copy /z "%~f0" nul') do set "CR=%%a"
<nul set /p =Hello, world!CR!
<nul set /p =Hi   ,
pause >nul

output:

Hi   , world

!CR! moves the cursor to the beginning of the line so either echo or <nul set /p = can overwrite that line without CLS.

What I'm asking is, can I do the exact same thing but for the entire console window (not just a line)? Or, can I move the cursor to the very beginning of the console so I can overwrite everything?

I knew I can just use CLS to wipe everything but I hate the flickering CLS makes when it deletes everything and then ECHO something else immediately.

I'm trying to make an interactive UI in Batch so any possible solutions will help a lot.


Solution

  • Just put !ESC![<line>;<column>H into you ECHO output. As well as the function

    for /F %%a in ('ECHO prompt $E ^| cmd') do (
      SET "ESC=%%a"
    )
    

    somewhere into your script.

    @ECHO OFF
    SETLOCAL EnableDelayedExpansion
    
    for /F %%a in ('ECHO prompt $E ^| cmd') do (
      SET "ESC=%%a"
    )
    
    ECHO Normal ECHO
    ECHO !ESC![3;2HWrite A
    ECHO !ESC![6;12HB
    ECHO !ESC![4;20HC
    ECHO !ESC![1;30HD Note: The cursor will now be in the line after this
    ECHO ECHO normal again
    
    PAUSE >NUL
    

    Output:

    ECHO in row and column

    Alternatively have a look into this tool: https://github.com/TheBATeam/BATBOX-An-Awesome-Batch-Plugin