首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >不记录Console.ReadLine输出?

不记录Console.ReadLine输出?
EN

Stack Overflow用户
提问于 2013-09-15 15:38:57
回答 3查看 592关注 0票数 1

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

EN

回答 3

Stack Overflow用户

发布于 2013-09-15 16:17:13

如果出于非安全原因而希望隐藏输入,那么使用ReadKey或各种方法来隐藏输入是相当繁琐的。可以直接使用Windows API完成此操作。我在搜索时发现的一些示例代码不能立即工作,但下面的代码可以。

但是,如果您隐藏的输入是出于安全考虑(例如密码),则首选使用ReadKeySecureString,因为不会生成包含密码的string对象(然后在内存中挂起,直到GC为止)。

代码语言:javascript
运行
复制
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);
        }
    }
}
票数 3
EN

Stack Overflow用户

发布于 2013-09-15 15:45:06

您需要使用Console.ReadKey(true)方法,逐个字符地读取输入的字符。

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

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

票数 2
EN

Stack Overflow用户

发布于 2013-09-15 16:34:29

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

代码语言:javascript
运行
复制
ConsoleColor forecolor = Console.ForegroundColor;
Console.ForegroundColor=Console.BackgroundColor;
string test=Console.ReadLine();
Console.ForegroundColor = forecolor;
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18810060

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档