Juergen
Juergen

Reputation: 55

How to distinguish between Enter and Escape key presses in interactive Windows bat/cmd scripts (cmd.exe)?

The Pause command exits on Enter and Escape keys, but does not return a distinctive ErrorLevel.
The Choice command does not return when pressing any of the Enter or Escape keys.

Upvotes: 3

Views: 7410

Answers (2)

David Ruhmann
David Ruhmann

Reputation: 11367

I found this question interesting and wanted to add one other possible solution, powershell ReadKey

Command

PowerShell Exit($host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown').VirtualKeyCode);


Usage

@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


References
TechNet
PS Pause Alternative

Upvotes: 0

jeb
jeb

Reputation: 82247

For detecting ENTER you can use XCOPY, really...
But detecting a single ESC seems not possible with pure 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 xcopy /L /W asks for a keypress to start copying and then it shows the key and ends.

Upvotes: 3

Related Questions