不记录Console.ReadLine输出?

时间:2013-09-15 07:38:57

标签: c#

当用户在Console.ReadLine中插入内容时,我怎么能不显示输出,这样控制台就不会显示用户输入的内容?谢谢!

3 个答案:

答案 0 :(得分:3)

如果由于非安全原因而想要隐藏输入,使用ReadKey或各种方法来隐藏输入是相当繁琐的。它可以使用Windows API直接完成。我在搜索时发现的一些示例代码不能立即生效,但下面的代码确实如此。

但是,对于您隐藏的输入是为了安全(例如密码)的情况,使用ReadKeySecureString将是首选,因为包含密码的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);
        }
    }
}

答案 1 :(得分:2)

您需要使用Console.ReadKey(true)方法并按字符读取输入字符。

如果您需要继续使用ReadLine,则解决方法是将前景色和背景色设置为相同的值。

如果您只想清除用户输入的内容,请使用Console.SetCursorPosition()方法并写入空格以覆盖用户编写的内容,或使用Console.Clear()清除整个屏幕。

答案 2 :(得分:0)

这可用于隐藏用户输入,但用户可以使用Console-> Properties

更改颜色
ConsoleColor forecolor = Console.ForegroundColor;
Console.ForegroundColor=Console.BackgroundColor;
string test=Console.ReadLine();
Console.ForegroundColor = forecolor;
相关问题