在 VB.NET 中,您如何能够从控制台读取少于标准的 254 个字符Console.ReadLine()
?
我试过使用Console.ReadKey()
:
Dim A As String = ""
Dim B As Char
For i = 0 To 10
B = Console.ReadKey().KeyChar
A = A & B
Next
MsgBox(A)
它限制了我并返回字符串,但如果用户输入少于 10 个字符,它怎么能工作呢?
在 VB.NET 中,您如何能够从控制台读取少于标准的 254 个字符Console.ReadLine()
?
我试过使用Console.ReadKey()
:
Dim A As String = ""
Dim B As Char
For i = 0 To 10
B = Console.ReadKey().KeyChar
A = A & B
Next
MsgBox(A)
它限制了我并返回字符串,但如果用户输入少于 10 个字符,它怎么能工作呢?
要将输入限制为 10 个字符,同时允许通过按 Enter 键输入少于 10 个字符,您可以使用这样的循环。它检查输入键并在按下时退出循环,否则一旦输入 10 个字符,循环自然会结束。
编辑 - 根据评论更新
Imports System.Text
Module Module1
Sub Main()
Dim userInput = New StringBuilder()
Dim maxLength = 10
While True
' Read, but don't output character
Dim cki As ConsoleKeyInfo = Console.ReadKey(True)
Select Case cki.Key
Case ConsoleKey.Enter
' Done
Exit While
Case ConsoleKey.Backspace
' Last char deleted
If userInput.Length > 0 Then
userInput.Remove(userInput.Length - 1, 1)
Console.Write(vbBack & " " & vbBack)
End If
Case Else
' Only append if less than max entered and it's a display character
If userInput.Length < maxLength AndAlso Not Char.IsControl(cki.KeyChar) Then
userInput.Append(cki.KeyChar)
Console.Write(cki.KeyChar)
End If
End Select
End While
MsgBox("'" & userInput.ToString() & "'")
End Sub
End Module