Normally in a Winform application, a TextBox is used for users to type in their password and it's very easy to mask the typed in password by setting the TextBox.PasswordChar property to whatever character you want to used as the mask. However, in a console application, it's not so simple. For each keystroke, we have to read the ConsoleKeyInfo, save the character, wipe out what the use just typed on screen to replace it with a password mask character.
This little function does just that.
vb.net Code:
Private Function GetPassword(Optional ByVal passwordMask As Char = "*"c) As String Dim pwd As String = String.Empty Dim sb As New System.Text.StringBuilder() Dim cki As ConsoleKeyInfo = Nothing 'Get the password Console.Write("Enter password: ") While (True) While Console.KeyAvailable() = False System.Threading.Thread.Sleep(50) End While cki = Console.ReadKey(True) If cki.Key = ConsoleKey.Enter Then Console.WriteLine() Exit While ElseIf cki.Key = ConsoleKey.Backspace Then If sb.Length > 0 Then sb.Length -= 1 Console.Write(ChrW(8) & ChrW(32) & ChrW(8)) End If Continue While ElseIf Asc(cki.KeyChar) < 32 OrElse Asc(cki.KeyChar) > 126 Then Continue While End If sb.Append(cki.KeyChar) Console.Write(passwordMask) End While pwd = sb.ToString() Return pwd End Function




Reply With Quote