This simple example provides you with a template to get the password from a user without displaying on the screen what they typed, and also accepting the backspace key when they press it.
The code;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Runtime.InteropServices;
namespace FirstOne
{
class Program
{
// Get the kernel function for setting console modes
[System.Runtime.InteropServices.DllImport("kernel32 ")]
private static extern int SetConsoleMode(IntPtr hConsoleHandle, int dwMode);
// Get the kernel function for getting console modes
[System.Runtime.InteropServices.DllImport("kernel32 ")]
private static extern int GetConsoleMode(IntPtr hConsoleHandle, ref int dwMode);
// Some useful constants for the console values
private const int ENABLE_LINE_INPUT = 2;
private const int ENABLE_ECHO_INPUT = 4;
// Standard input file handle
private const int CONIN = 3;
// Ensure that our process is single threaded as we as using COM and need to ensure communication
[STAThread]
static void Main(string[] args)
{
IntPtr hStdIn = new IntPtr(CONIN);
int myMode=0;
char inputChar;
string password = "";
Console.Write("Password: ");
// Get the current console settings
GetConsoleMode(hStdIn, ref myMode);
// Turn off echo
myMode = (myMode & ~(ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT));
SetConsoleMode(hStdIn, myMode);
do
{
inputChar = (char)Console.Read();
if (inputChar == '\b') // Can also use 8 instead of '\b'
{
// Delete character if user has pressed backspace
password=password.Remove(password.Length-1);
}
if (inputChar >= 32)
{
// Store password characters
password += inputChar;
}
} while (inputChar != '\r');
// Reset terminal echo
myMode = (myMode | (ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT));
SetConsoleMode(hStdIn, myMode);
Console.WriteLine("");
Console.WriteLine("Password was: {0}", password);
}
}
}
No comments:
Post a Comment