如何在VB.NET中使用Console.ReadLine()
从控制台读取少于标准的254个字符?
我尝试过使用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个字符,它怎么能工作呢?
答案 0 :(得分:1)
要将输入限制为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