C#隐藏控制台键盘输入的方法
本文实例讲述了C#隐藏控制台键盘输入的方法。分享给大家供大家参考。具体如下:
usingSystem;
namespaceRobvanderWoude
{
classHideInput
{
staticintMain(string[]args)
{
try
{
boolclearscreen=false;
if(args.Length>1)
{
returnWriteError("Toomanycommandlinearguments");
}
if(args.Length==1)
{
switch(args[0].ToUpper())
{
case"/C":
clearscreen=true;
break;
case"/?":
returnWriteError();
default:
returnWriteError("Invalidcommandlineargument\""+args[0]+"\"");
}
}
//Setconsoleforegroundcolortobackgroundcolortohidewhat'sbeingtyped
ConsoleColorcolor=Console.ForegroundColor;
Console.ForegroundColor=Console.BackgroundColor;
//Read1lineofinputfromtheconsole
stringinput=Console.ReadLine();
//Restoretheoriginalconsoleforegroundcolor
Console.ForegroundColor=color;
//Clearthescreenidspecifiedonthecommandline
if(clearscreen)
{
Console.Clear();
}
//Displaytheinput-whichshouldberedirectedforthisprogramtobeofanyuse
Console.WriteLine(input);
//Returncode0forsuccess,or1iftheinputwasemptyorwhitespaceonly
if(string.IsNullOrWhiteSpace(input))
{
return1;
}
else
{
return0;
}
}
catch(Exceptione)
{
returnWriteError(e.Message);
}
}
publicstaticintWriteError(stringerrorMessage="")
{
Console.ResetColor();
if(string.IsNullOrEmpty(errorMessage)==false)
{
Console.Error.WriteLine();
Console.ForegroundColor=ConsoleColor.Red;
Console.Error.Write("ERROR:");
Console.ForegroundColor=ConsoleColor.White;
Console.Error.WriteLine(errorMessage);
Console.ResetColor();
}
Console.Error.WriteLine();
Console.Error.WriteLine("HideInput,Version1.10");
Console.Error.WriteLine("Batchutilitytoread1lineofinputwhilehidingwhat'sbeingtyped,by");
Console.Error.WriteLine("temporarilysettingtheconsoleforegroundcolorequaltoitsbackgroundcolor");
Console.Error.WriteLine();
Console.Error.Write("Usage:FOR/F\"tokens=*\"%%AIN('");
Console.ForegroundColor=ConsoleColor.White;
Console.Error.Write("HIDEINPUT");
Console.ResetColor();
Console.Error.WriteLine("')DOSETpassword=%%A");
Console.Error.Write("or:FOR/F\"tokens=*\"%%AIN('");
Console.ForegroundColor=ConsoleColor.White;
Console.Error.Write("HIDEINPUT/C");
Console.ResetColor();
Console.Error.WriteLine("')DOSETpassword=%%A");
Console.Error.WriteLine();
Console.Error.Write("Where:");
Console.ForegroundColor=ConsoleColor.White;
Console.Error.Write("/C");
Console.ResetColor();
Console.Error.WriteLine("clearsthescreentoremovewhat'stypedfromthescreenbuffer");
Console.Error.WriteLine();
Console.Error.WriteLine("WrittenbyRobvanderWoude");
return1;
}
}
}
希望本文所述对大家的C#程序设计有所帮助。