Search code examples
batch-filetimeout

windows batch scripting: catch user reaction to "timeout" command


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


Solution

  • 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