I've encountered a bit of an issue in a Batch script I am making. In this script, I want to it react to my pressing a button the moment I press it, and 'set'ting a new variable without having to press Enter. Currently, it's like this;

set b=
set /p b=
ig %b%==a (
goto Success
)

It allows me to press the button I want, however I don't want it to wait until I press Enter afterwards.

有帮助吗?

解决方案

For VISTA and later

If you know your script will run on Vista or later (not XP), then you can use the choice command. You must specify which characters to accept. By default, CHOICE is case insensitive. The returned ERRORLEVEL corresponds to the position of the selected letter within the choice list.

For example, to wait for the user to press A, B, or C (case sensitive) and store the key value in a variable:

setlocal enableDelayedExpansion
set "list=ABC"
choice /cs /c "%list%"
set "list=.%list%"
set "key=!list:~%errorlevel%,1!"
echo %key%

Full documentation is available from the command line by typing HELP CHOICE or CHOICE /?

For all modern Windows, including XP

I was introduced to a very clever solution that works on XP and beyond when I was developing my batch implementation of the SNAKE game. This solution allows you to capture nearly any key press.

set "key="
for /F "usebackq delims=" %%A in (`xcopy /w "%~f0" "%~f0" 2^>NUL`) do (
  if not defined key set "key=%%A"
)
set "key=%key:~-1%"
set key

其他提示

use choice in batch

choice /c YN /m "Is Yes"
if ( %ERRORLEVEL% == 1 ) (
   ECHO "SUCCESS"
)
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top