Search code examples
vb.netconsole-applicationconsole.readline

VB.NET Console.ReadLine() min length?


How would you be able to read less than the standard 254 characters from the console, in VB.NET with Console.ReadLine()?

I have tried using 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)

It limits me and it returns the string, but how could it work if a user was to enter less than 10 characters?


Solution

  • To limit the input to 10 characters, while allowing for less that 10 characters to be entered by pressing the Enter key, you can use a loop like this. It checks for the enter key and exits the loop if it's pressed, or the loop will naturally end once 10 characters have been entered.

    EDIT - updated per comments

    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