如何输入任何可见的单个字符,然后立即批处理CMD [复制]
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何输入任何可见的单个字符,然后立即批处理CMD [复制]相关的知识,希望对你有一定的参考价值。
这个问题在这里已有答案:
目标:我希望用户只键入一个字符(任何字符),然后脚本立即响应,无需额外按键“输入”键。如果用户键入“enter”键而没有先前输入的任何字符,则脚本将不响应。
我坚持使用这段代码:
@Echo Off
SET Alnum=abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890
:: ordinary symbol string would not work!
:: it must be escaped, but i don't know how.
SET Symbol=
SETLOCAL EnableExtensions EnableDelayedExpansion
CALL :CharInput "Type one char: "
ECHO Your input was: "!RetVal!"
ECHO(
CALL :CharInput "one more char: "
ECHO Your input was: "!RetVal!"
ECHO(
CALL :CharInput "still need more: "
ECHO Your input was: "!RetVal!"
ECHO(
GOTO :eof
:: @param1 %~1 message to print
:: @return RetVal the single character entered by user
:CharInput
IF "" == "!VisibleChars!" (
CALL :CharacterizedWord "%Alnum%%Symbol%"
SET VisibleChars=!RetVal!
)
SET /P "=%~1" < Nul
SET Found=false
FOR /F "skip=1" %%# IN ('REPLACE "%~f0" . /U /W') DO SET "CHR=%%#"
SET /P "=!CHR!" <Nul
FOR %%a in (!VisibleChars!) DO (
IF "%%a" == "!CHR!" (
SET Found=true
)
)
:: needs work around to make the script print only 1 message
:: each time the user presses the "enter" key
:: without any visible characters previously entered
IF "false" == "!Found!" (
ECHO(
GOTO :CharInput
) ELSE (
SET "RetVal=!CHR!"
ECHO(
)
GOTO :eof
:: @param1 %~1 the word being characterized
:: @return RetVal the string contains words each of single character
:CharacterizedWord
SET Word=%~1
SET tempstr=%~1
SET count=0
:CharacterizedWordLoop
IF DEFINED tempstr (
SET tempstr=%tempstr:~1%
SET /a count+=1
SET /a pos=%count%-1
SET RetVal=!RetVal! !Word:~%pos%,1!
GOTO :CharacterizedWordLoop
)
GOTO :eof
- 我尝试过任何组合将所有符号字符收集到一个单词中。任何人都可以帮助我填补“符号”var的空虚吗?
- 除了这个之外还有更好的算法来扩展可见字符列表而不必在每次找到新字符时编辑列表吗?
- 每次用户按下“回车”键时,此应用程序仍然打印“类型一个字符:”消息。谁能解决这个问题?
答案
在控制台中,$ host ReadKey方法可用于读取单个键而不需要Enter键。这会做你想要的吗?
将其放入名为“thekey.ps1”的文件中。
<# Ignore:
Enter
Shift
Ctrl
Alt 18
CapsLock
LeftArrow
RightArrow
UpArrow
DownArrow
Delete
End 35
Home 36
Insert 45
PgUp 33
PgDown 34
Windows 91
#>
$nowatch = $(13, 16, 17, 18, 20, 37, 38, 39, 40, 46, 35, 36, 45, 33, 34, 91)
do {
$key = $host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown')
#$key.VirtualKeyCode
$vkc = $key.VirtualKeyCode
$k = $key.Character
} while ($nowatch -contains $vkc)
$k
如果您需要发现其他密钥,请从#$key.VirtualKeyCode
中删除注释“#”并在PowerShell控制台(而非ISE)中运行。\ thekey.ps1。
将其放入名为“thekey.bat”的文件中。
@ECHO OFF
:Head
FOR /F "usebackq tokens=*" %%k IN (`powershell -NoProfile -File .\thekey.ps1`) DO (
SET "THEKEY=%%k"
)
ECHO THEKEY is %THEKEY%
GOTO Head
或者:
指定要识别的键可能更容易,而不是指定的键。
$keylist = @()
0x21..0x7E | ForEach-Object { $keylist += $_ }
do {
$key = $host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown')
#$key.VirtualKeyCode
$vkc = $key.VirtualKeyCode
$k = $key.Character
} while ($keylist -notcontains $vkc)
$k
以上是关于如何输入任何可见的单个字符,然后立即批处理CMD [复制]的主要内容,如果未能解决你的问题,请参考以下文章