使用批处理循环直到按下任何键

loop using batch until any key is pressed

我最近做了这个小代码。

@echo off
mode 1000
set /A x=0
:loop
timeout /T 1 > Nul /nobreak
set /A x=x+1
echo %X%
goto loop

有人可以帮我编辑这段代码,让它循环,直到按下任意键然后停止循环吗?我是使用 Batch 编码的新手,因此不知道该怎么做 :(

我认为删除 /nobreak 应该会有帮助

在其他活动正在进行时等待按键在批处理脚本中并不是那么简单。

然而,这里有一个不完美但非常简单的 semi-solution 使用 choice and ErrorLevel:

@echo off
set /A "X=0"
:LOOP
rem /* `choice is utilised; all (case-insensitive) letter and numeral keys (excluding
rem    key `0`) are defined to quit the loop; `choice` features a timeout, upon which
rem    the default choice (key `0` here) is taken: */
choice /C abcdefghijklmnopqrstuvwxyz1234567890 /T 1 /D 0 > nul
rem /* `choice` reflects the actually pressed key in the `ErrorLevel` value, meaning
rem    `ErrorLevel = 1` reflects the first key `a`, and `ErrorLevel = 36` reflects
rem    the last one in the list, `0`; since the default choice after the timeout is
rem    `0`, pressing the `0` key has got the same effect as not pressing any key: */
if ErrorLevel 1 if not ErrorLevel 36 goto :QUIT
set /A "X+=1"
echo %X%
goto :LOOP
:QUIT

choice 方法 () 也是我的第一个想法,但它与您的“任意键”要求相矛盾。

因此我使用了不同的方法:在后台启动另一个实例,它只是等待一个键(pause),然后创建一个文件。
一旦文件存在,主循环就会退出。

@echo off 
setlocal
start /b cmd /c "pause >nul & break>flag"
del flag >nul 2>&1
:loop
if exist flag goto :done
timeout 1 >nul
set /a count+=1
echo %count%
goto :loop
:done
del flag >nul 2>&1
echo interrupted by a key press.