How to distinguish between Enter and Escape key presses in interactive bat / cmd Windows scripts (cmd.exe)?
I found this question interesting and wanted to add another possible solution, powershell ReadKey
Command
PowerShell Exit($host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown').VirtualKeyCode);
Using
@echo off
set /p "=> Single Key Prompt? " <nul
PowerShell Exit($host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown').VirtualKeyCode);
echo KeyCode = %ErrorLevel%
Output: enter key
> Single Key Prompt? KeyCode = 13
Output: Escape Key
> Single Key Prompt? KeyCode = 27
TechNet
Links
PS Pause Alternative
source to share
To detect ENTER you can use XCOPY, really ...
But detecting a single ESC seems impossible with a clean batch.
setlocal EnableDelayedExpansion
call :GetKey
if "!key!"=="" echo ENTER
if "!key!"==" " echo SPACE
exit /b
:GetKey
set "key="
for /F "usebackq delims=" %%L in (`xcopy /L /w "%~f0" "%~f0" 2^>NUL`) do (
if not defined key set "key=%%L"
)
set "key=%key:~-1%"
exit /b
This works as it xcopy /L /W
asks for a key press to start copying and then shows the key and ends.
source to share
You can do this using select32.exe ( http://www.westmesatech.com/editv.html ):
choose32 -c ^A^[ -d ^A -q -n -p "ESC to quit, ENTER to continue: "
^ A - Ctrl + A (ASCII character 1) and ^ [- Ctrl + [(ASCII character 27 or Esc). Breakout command line:
- -c specifies which keys are valid (in this case Ctrl + A and Esc).
- -d specifies which choice to use if you press Enter (default choice).
- -n hides the list of options.
- -q does not display keystrokes.
- -p Specifies the prompt to display.
In this case, select32 returns exit code 2 if Esc was pressed, or exit code 1 if Enter was pressed.
source to share