当用户在 Console.ReadLine 中插入内容时,如何不显示输出,这样控制台就不会显示用户输入的内容?谢谢!
问问题
593 次
3 回答
3
如果您出于非安全原因想要隐藏输入,则使用ReadKey
各种方法来隐藏输入是相当乏味的。它可以直接使用 Windows API 完成。我在搜索时发现的一些示例代码并没有立即生效,但下面的代码可以。
但是,对于您隐藏的输入是为了安全(例如密码)的情况,使用ReadKey
andSecureString
将是首选,因为string
不会生成包含密码的对象(然后在内存中徘徊直到 GC)。
using System;
using System.Runtime.InteropServices;
namespace Test
{
public class Program
{
[DllImport("kernel32")]
private static extern int SetConsoleMode(IntPtr hConsole, int dwMode);
// http://msdn.microsoft.com/en-us/library/windows/desktop/ms683167(v=vs.85).aspx
[DllImport("kernel32")]
private static extern int GetConsoleMode(IntPtr hConsole, out int dwMode);
// see http://msdn.microsoft.com/en-us/library/windows/desktop/ms683231(v=vs.85).aspx
[DllImport("kernel32")]
private static extern IntPtr GetStdHandle(int nStdHandle);
// see docs for GetStdHandle. Use -10 for STDIN
private static readonly IntPtr hStdIn = GetStdHandle(-10);
// see docs for GetConsoleMode
private const int ENABLE_ECHO_INPUT = 4;
public static void Main(string[] args)
{
Console.WriteLine("Changing console mode");
int mode;
GetConsoleMode(hStdIn, out mode);
SetConsoleMode(hStdIn, (mode & ~ENABLE_ECHO_INPUT));
Console.WriteLine("Mode set");
Console.Write("Enter input: ");
string value = Console.ReadLine();
Console.WriteLine();
Console.WriteLine("You entered: {0}", value);
}
}
}
于 2013-09-15T08:17:12.933 回答
2
您需要使用Console.ReadKey(true)
方法并逐个字符地读取输入。
如果您需要继续使用,一种解决方法ReadLine
是将前景色和背景色设置为相同的值。
如果您只想清除用户输入的内容,请使用Console.SetCursorPosition()
方法和写入空格来覆盖用户写入的内容或使用Console.Clear()
清除整个屏幕。
于 2013-09-15T07:45:05.777 回答
0
这可用于隐藏用户输入,但用户可以使用 Console->Properties 更改颜色
ConsoleColor forecolor = Console.ForegroundColor;
Console.ForegroundColor=Console.BackgroundColor;
string test=Console.ReadLine();
Console.ForegroundColor = forecolor;
于 2013-09-15T08:34:29.480 回答