我可以在 Cmd 中创建一个带有计时器的 'set /p ""=' 命令吗?
Posted
技术标签:
【中文标题】我可以在 Cmd 中创建一个带有计时器的 \'set /p ""=\' 命令吗?【英文标题】:Can I create a 'set /p ""=' command with a timer in Cmd?我可以在 Cmd 中创建一个带有计时器的 'set /p ""=' 命令吗? 【发布时间】:2016-02-14 14:35:50 【问题描述】:我想为 'set /p ""=' 命令创建一个计时器,这样如果您没有在所需的时间空间内输入内容,它就会移动到不同的标签。
例如。
echo You have 3 seconds to type 'go'
(??if not typed in 3 seconds goto fail??)
set /p input=
if %input%==go goto win
goto fail
是否可以命令程序在“set /p”之前设置一个 3 秒的计时器?不将其与 C# 等其他语言混合使用?
【问题讨论】:
您可以使用 CHOICE 命令,但它只接受单个字符的输入。 非常感谢大家!这两个答案正是我想要的。 【参考方案1】:我在this post 得到了答案,并稍作修改以满足这个要求。
@echo off
setlocal EnableDelayedExpansion
rem Execute a SET /P command with time out
rem Antonio Perez Ayala
rem If this file is re-executed as pipe's right side, go to it
if "%~1" equ "TimeoutMonitor" goto %1
del InputLine.txt 2> NUL
(
set /P "input=You have 3 seconds to type 'go': " > CON
> InputLine.txt call set /P "=%%input%%" < NUL
) 2> NUL | "%~F0" TimeoutMonitor 3
set /P "input=" < InputLine.txt
del InputLine.txt
if /I "%input%" equ "go" (
echo You did it^^!
) else (
echo you failed...
)
goto :EOF
:TimeoutMonitor
rem Get the PID of pipe's left side
tasklist /FI "IMAGENAME eq cmd.exe" /FO TABLE /NH > tasklist.txt
for /F "tokens=2" %%a in (tasklist.txt) do (
set "leftSidePipePID=!lastButOnePID!"
set "lastButOnePID=%%a"
)
del tasklist.txt
rem Wait for the input line, or until the number of seconds passed
for /L %%i in (1,1,%2) do (
ping -n 2 localhost > NUL
if exist InputLine.txt exit /B
)
rem Timed out: kill the SET /P process and create a standard input line
taskkill /PID %leftSidePipePID% /F > NUL
echo/
echo Timed Out> InputLine.txt
exit /B
【讨论】:
Aacini++。花哨的解决方案。【参考方案2】:Squashman 的建议也是我想到的最好的建议。保存以下 .bat 脚本并运行它,看看它是否提供了您想要的用户体验。
@echo off
setlocal
set /P "=You have 3 seconds to type 'go': "<NUL
rem // capture an extended character as a default option for "choice"
for /f %%I in ('forfiles /p "." /m "%~nx0" /c "cmd /c echo 0x99"') do set "char=%%~I"
rem // for each letter in "go"...
for %%I in (g o) do (
choice /c %%I%char% /t 3 /d %char% >NUL
rem // Extended character probably isn't on the keyboard.
rem // If the result was the extended char, it was timed out.
if errorlevel 2 goto fail
rem // visual response of user input w/o new line
set /P "=%%I"<NUL
)
echo;
echo You did it!
pause & goto :EOF
:fail
echo;
echo Too slow.
pause
【讨论】:
以上是关于我可以在 Cmd 中创建一个带有计时器的 'set /p ""=' 命令吗?的主要内容,如果未能解决你的问题,请参考以下文章