objective:我希望用户仅键入一个字符(任何字符),然后脚本立即响应而没有其他" Enter"键的键。如果用户类型" 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的空虚?
除此之外,还有更好的算法以扩展可见的字符列表,而无需每次找到新字符时编辑列表?
此应用程序仍在打印" type One Char:"消息每次用户按" Enter"键时。任何人都可以解决此问题吗?
在控制台中,$ host readkey方法可用于读取无需输入密钥的单个键。这会像您想要一样吗?
将其放入名为" 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
中删除注释'#'并运行。
将其放入名为" 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