当 运行 循环时按下按钮时执行命令的批处理
Batch which carries out a command when a button is pressed while running a loop
我想要 运行 一个循环并让它在按下某个键时循环结束,就像下面的内容一样,尽管它不起作用。
此外,循环必须继续 运行ning 而不是在等待用户输入时停止。
@echo off
:start
echo 1
IF "a"=="" GOTO end
goto :start
:end
pause
您指的是多线程(一个线程接受输入,一个 运行 循环)。有一些棘手的方法可以做到这一点。然而,为了节省您的时间和精力,您可以使用一个廉价的技巧,即在每次迭代时保持循环一秒钟,然后使用 choice
命令等待输入:
@echo off
:start
echo 1
choice /c "qa" /d q /t 1 /n /m "Press a to Stop Loop: "
if %errorlevel%==2 goto end
cls
goto :start
:end
pause
它将每秒停止一次以检查输入 a
这在所有批处理脚本中自动工作,只要特定键是 Ctrl+C
。
否则,您需要在循环的每次迭代中进行检查(就像您所做的那样),并需要另一个进程来监视键盘。
:: Allocate a probably-unique filename
set SENTINELFILE=%temp%\sentinel-%random%-%time:~6,5%.lck
:: Should probably do something less destructive if the file already exists
:: like loop and find another name. But this is a prototype.
copy /y NUL %SENTINELFILE%
:: Opens a new cmd window which prompts the user to press X
:: then deletes the sentinel and exits
:: Could also run another batch file or exe that does something we can detect
start "End Task" %comspec% /c choice /c x /M "Press X to end task" ^& del %SENTINELFILE%
:topofloop
:: TODO: Process some part of your work to be done
:: Loop as long as the sentinel file exists
if exist %SENTINELFILE% goto :topofloop
我想要 运行 一个循环并让它在按下某个键时循环结束,就像下面的内容一样,尽管它不起作用。 此外,循环必须继续 运行ning 而不是在等待用户输入时停止。
@echo off
:start
echo 1
IF "a"=="" GOTO end
goto :start
:end
pause
您指的是多线程(一个线程接受输入,一个 运行 循环)。有一些棘手的方法可以做到这一点。然而,为了节省您的时间和精力,您可以使用一个廉价的技巧,即在每次迭代时保持循环一秒钟,然后使用 choice
命令等待输入:
@echo off
:start
echo 1
choice /c "qa" /d q /t 1 /n /m "Press a to Stop Loop: "
if %errorlevel%==2 goto end
cls
goto :start
:end
pause
它将每秒停止一次以检查输入 a
这在所有批处理脚本中自动工作,只要特定键是 Ctrl+C
。
否则,您需要在循环的每次迭代中进行检查(就像您所做的那样),并需要另一个进程来监视键盘。
:: Allocate a probably-unique filename
set SENTINELFILE=%temp%\sentinel-%random%-%time:~6,5%.lck
:: Should probably do something less destructive if the file already exists
:: like loop and find another name. But this is a prototype.
copy /y NUL %SENTINELFILE%
:: Opens a new cmd window which prompts the user to press X
:: then deletes the sentinel and exits
:: Could also run another batch file or exe that does something we can detect
start "End Task" %comspec% /c choice /c x /M "Press X to end task" ^& del %SENTINELFILE%
:topofloop
:: TODO: Process some part of your work to be done
:: Loop as long as the sentinel file exists
if exist %SENTINELFILE% goto :topofloop