I am writing a console application using BDE 2006 and I want it to be able to prompt for a password string and mask it with "*" as the user is typing. I have looked around but I could not find examples of how to do this. Everything I saw was how to do this in TEdit. Any pointers on how to accomplish this?
Thanks in advance,
Nic
string pass = ""; Console. Write("Enter your password: "); ConsoleKeyInfo key; do { key = Console. ReadKey(true); // Backspace Should Not Work if (key. Key !=
Password masking is the act of hiding passwords as bullets or asterisks when the user enters the password. Password masking is an attempt to protect the user against shoulder surfers who look at the screen.
Open Visual Studio, and choose Create a new project in the Start window. In the Create a new project window, select All languages, and then choose C# from the dropdown list. Choose Windows from the All platforms list, and choose Console from the All project types list.
Here's a working solution:
program Project2;
{$APPTYPE CONSOLE}
uses
SysUtils, Windows;
function GetPassword(const InputMask: Char = '*'): string;
var
OldMode: Cardinal;
c: char;
begin
GetConsoleMode(GetStdHandle(STD_INPUT_HANDLE), OldMode);
SetConsoleMode(GetStdHandle(STD_INPUT_HANDLE), OldMode and not (ENABLE_LINE_INPUT or ENABLE_ECHO_INPUT));
try
while not Eof do
begin
Read(c);
if c = #13 then // Carriage Return
Break;
Result := Result + c;
if c = #8 then // Back Space
Write(#8)
else
Write(InputMask);
end;
finally
SetConsoleMode(GetStdHandle(STD_INPUT_HANDLE), OldMode);
end;
end;
begin
try
Writeln(Format(sLineBreak + 'pswd=%s',[GetPassword]));
Readln;
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
end.
Update: Note that the above code handles the BackSpaces visually, but keeps them embedded in the password, which might not be what you want.
In that case the following code would filter them out:
if c = #13 then // Carriage Return
Break;
if (c = #8) and (Length(Result) > 0) then // Back Space
begin
Delete(Result, Length(Result), 1);
Write(#8);
end
else
begin
Result := Result + c;
Write(InputMask);
end;
I have a unit with procedure ConsoleGetPassword(const caption: String; var Password: string);
which does what you want
see http://gist.github.com/570659
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With