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