Snippets

Cameron Presley F# - Masked console input

Created by Cameron Presley
// Port of http://www.c-sharpcorner.com/Forums/Thread/32102/password-in-C-Sharp-console-application.aspx
let getMaskedInput () =
    let rec processKey (info:ConsoleKeyInfo) (input:string) = 
        match info.Key with
        | ConsoleKey.Enter -> 
            Console.WriteLine()
            input
        | ConsoleKey.Backspace ->
            if not (String.IsNullOrWhiteSpace(input)) then
                let input' = password.Substring(0, input.Length - 1)
                let pos = Console.CursorLeft
                Console.SetCursorPosition(pos - 1, Console.CursorTop)
                Console.Write(" ")
                Console.SetCursorPosition(pos - 1, Console.CursorTop)
                processKey (Console.ReadKey(true)) input'
            else
                processKey (Console.ReadKey(true)) input
        | _ ->
            Console.Write("*")
            processKey (Console.ReadKey(true)) (input + info.KeyChar.ToString())

    processKey (Console.ReadKey(true)) ""

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.