windows batch scripting: catch user reaction to “t

2019-06-20 04:27发布

I know that by using the "timeout" command, I can wait for specified amount of time; but my question is that what if this would be an automatic operation that could be prevented by user? I mean suppose that I wanted to do the operation A but by using the "timeout" command I wait if user wants to cancel this operation or not; for example during this waiting process if user pressed the Enter key then batch script execute something else(not operation A);enter image description here

3条回答
仙女界的扛把子
2楼-- · 2019-06-20 04:56

timeout is just to induce a delay before an action, not to let the user choose something. I f you still want to use it, you need to ask the user to press Control-C to break before the timeout command, and catch the ERRORLEVEL after that.

Else choice is your friend here:

C:\Users\mm>CHOICE /T 10 /C yYcC /CS /D y  /M "Press y to validate, c to Cancel. You have 10 sec delay [Default y]:"
Press y to validate, c to Cancel. You have 10 sec delay [Default y]: [y,Y,c,C]?y

And you can test returned value with ERRORLEVEL. Here, I pressed nothing, so y get selected (default value via /D) and ERRORLEVEL is 1 (1st option). The countdown is not displayed though.

choice.exe reference at ss64.com

查看更多
爷的心禁止访问
3楼-- · 2019-06-20 05:05

As indicated by Aacini, no, timeout has been built without this feature.

This can be used as a workaround

@echo off

    call :controlTimeout 5
    if errorlevel 1 (
        echo timeout was cancelled
    ) else (
        echo timeout reached
    )

    exit /b 

:controlTimeout 
    setlocal
    start "" /belownormal /b cmd /q /d /c "timeout.exe %~1 /nobreak > nul"
    timeout.exe %~1 & tasklist | find "timeout" >nul 
    if errorlevel 1 ( set "exitCode=0" ) else ( 
        set "exitCode=1"
        taskkill /f /im timeout.exe 2>nul >nul
    )
    endlocal & exit /b %exitCode%

This just starts two instances of timeout, one in background that is only cancelable with Ctrl+C and one in the active console. When the timeout command in console finished, tasklist is used to determine if the background timeout task is still active. If it is, then the visible timeout has been canceled, else timeout has been reached.

查看更多
我命由我不由天
4楼-- · 2019-06-20 05:15

Wow! I always thought that this capability was inherent to timeout, but it is not! There is no way to know if timeout command ends because the time out or because a key press...

However, it is possible to know if the time out was cancelled by Ctrl-C, instead by a normal key! In this case, the errorlevel value returned by timeout is different than zero:

C:\> timeout 60

Waiting for 47^Ceconds, press a key to continue ...
C:\> echo %errorlevel%
-1073741510

However, if you use this command inside a Batch file, the Ctrl-C press also cancel its execution! So the answer is: NO, there is no way to detect this point... :-(

查看更多
登录 后发表回答