批处理:按住输入时如何防止循环代码

Batch: How to prevent looping code when holding enter

所以我在这里做了一些事情,其中​​会有一个数字列表,例如 1-10,无论您键入哪个数字(到目前为止只有 1)都会向您显示信息(所以如果我键入并输入 1,它会去 key1=key).

但是,如果我键入 1 并单击回车,它会显示我想要的 Key1 = 键,但是如果我按住 Enter 键,它将继续循环 Key1=Key 脚本和主页,可以这要停止了吗?

@echo off
:T
cls

echo Home Page
echo [1] NameA
echo.
echo [e] Exit

set /p word=
if "%word%"=="1" goto aaa
if "%word%"=="e" goto eee
goto T

:aaa
cls
echo Key1 = Key
pause
goto T

:eee
exit

set /p 保留最后一个值,如果你只是按 enter。您应该将变量设置为空(或默认值,如果您愿意):

@echo off
:loop
REM set "word="  ; for "empty"
set "word=string"
set /p "word=Enter your choice (or just ENTER for '%word%': "
echo you choosed %word%
goto :loop

请注意 choice 命令,它可能(也可能不是)更好的选择。

@echo off
setlocal

:T
cls

echo Home Page
echo [1] NameA
echo.
echo [e] Exit

rem Undefine variable word before input.
set "word="

set /p "word="

rem No input = word is not set a new value, thus not defined.
if not defined word goto eee

if "%word%"=="1" goto aaa
if "%word%"=="e" goto eee
goto T

:aaa
cls
echo Key1 = Key
pause
goto T

:eee
exit

如果您仅在 set /p 提示符下按 Enter,则变量 word 未设置(新值)。 如果 wordset /p 输入之前未定义,那么在输入之后它将是未定义的, 如果您只按 Enter.

添加

setlocal 以保持当前脚本的本地变量设置 执行。