The timeout
command waits for the specified time and can be terminated by a key-ress, given that the option /NOBREAK
is not specified. It outputs a text like Waiting for 3 seconds, press a key to continue ...
and updates the seconds value each second by placing the cursor right to the number, then writing out as many backspace characters as needed and then overwriting the number. This whole text, including the backspaces, can be captured by a for /F
loop and then checked for the last number being 0
; if it is not, the user pressed a key, aborting the timeout
command.
This is how this approach could be coded:
@echo off
rem // Retrieve the backspace character:
for /F %%B in ('prompt $H ^& for %%B in ^(.^) do rem/') do set "_BS=%%B"
:SEARCH
rem // Improved filtering for the process:
tasklist /FI "ImageName eq notepad.exe" | find "=" > nul
if not ErrorLevel 1 goto :FOUND
rem /* Use `timeout` without `/NOBREAK` option to allow abortion of the waiting;
rem `timeout` counts down the seconds and precedes each number with backspace
rem characters, and the whole output string is captured by `for /F`; when no
rem key is pressed, then seconds reach `0`, otherwise not: */
for /F "delims=" %%T in ('timeout /T 3') do set "TOUT=%%T"
rem /* Now let us replace each backspace by `" "` and surround the whole string
rem with `""`, so we get space-separated quoted strings:
call set TOUT="%%TOUT:%_BS%=" "%%"
rem // Loop through those strings and assign each to the same variable:
for %%T in (%TOUT%) do set "TOUT=%%~T"
rem // The last string is now checked against `0`; if it is, no key was pressed:
if "%TOUT%"=="0" goto :SEARCH
rem // This point is only reached if a key-press aborted the `timeout` command.
:FOUND
exit /B