Can I create a 'set /p “”=' command with a timer in Cmd?

怎甘沉沦 提交于 2019-12-17 16:55:06

问题


I want to create a timer for the 'set /p ""=' command so that if you don't input something in the required time space it moves to a different label.

Eg.

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

Is it possible to command the program to set a 3 second timer before the 'set /p'? Without mixing it with another language like C# etc?


回答1:


Squashman's suggestion is the best one that comes to mind for me as well. Save the following .bat script and run it, and see whether it offers the user experience you had in mind.

@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



回答2:


I took the answer at this post and slightly modified it in order to fulfill this request.

@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


来源:https://stackoverflow.com/questions/33685518/can-i-create-a-set-p-command-with-a-timer-in-cmd

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!