> ## Content Index
> Fetch the complete content index at: https://blog.skitisu.com/llms.txt
> Use this file to discover other available public pages before exploring further.

# C#实现在控制台的密码输入（含星号和退格功能）
- URL: https://blog.skitisu.com/csharp-console-password-asterisk-backspace/
- Published: 2015-04-21T06:09:51.000Z
- Updated: 2019-06-01T18:58:24.000Z
- Author: SkiTiSu
- Tags: 探索, 编程, #Import 2026-10-21 14:41

[![EnterPasswd](https://blog.skitisu.com/wp-content/uploads/2015/04/EnterPasswd.jpg)](https://blog.skitisu.com/wp-content/uploads/2015/04/EnterPasswd.jpg)  
按照我的一贯风格，废话不说，直接上代码

/* 本段代码使用“天书我勒个去我还是相信中国开源的V0.9”协议发布
 * 如果您需在发布（包含商业与非商业）的软件中使用本代码，只需告知作者四季天书并在软件的关于里加上天书的名字即可
 * 因为我还是相信中国开源的。。。
 */
static string EnterPasswd()
{
    while (true)
    {
        Console.Write("请输入密码>");
        string key = string.Empty;
        while (true)
        {
            ConsoleKeyInfo keyinfo = Console.ReadKey(true);
            if (keyinfo.Key == ConsoleKey.Enter) //按下回车，结束
                break;
            else if (keyinfo.Key == ConsoleKey.Backspace && key.Length > 0) //如果是退格键并且字符没有删光
            {
                Console.Write("\b \b"); //输出一个退格（此时光标向左走了一位），然后输出一个空格取代最后一个星号，然后再往前走一位，也就是说其实后面有一个空格但是你看不见= =
                key = key.Substring(0, key.Length - 1);
            }

            else if (!char.IsControl(keyinfo.KeyChar)) //过滤掉功能按键等
            {
                key += keyinfo.KeyChar.ToString();
                Console.Write("*");
            }
        }
        return key;
    }
}

你们自己看吧，我觉得已经没什么bug了。。。

使用演示到[这里（链接到Github）](https://github.com/SkiTiSu/TSLib/blob/master/TSLib/Consoles/Passwd.cs?ref=blog.skitisu.com)看吧

天书2014年9月后的第一篇文章（本文）竟然是生病请假在家写的。。。

### 历史引用

- 【转载】C#实现在控制台的密码输入（含星号和退格功能） | αληθεια · 2015-07-19 23:04:32.000000  
> \[…\] 原文：C#实现在控制台的密码输入（含星号和退格功能） | 四季天书SkiTiSu’s blog… \[…\]  
[查看引用来源](http://aletheia.sinaapp.com/computer/c/300/%e3%80%90%e8%bd%ac%e8%bd%bd%e3%80%91c%e5%ae%9e%e7%8e%b0%e5%9c%a8%e6%8e%a7%e5%88%b6%e5%8f%b0%e7%9a%84%e5%af%86%e7%a0%81%e8%be%93%e5%85%a5%ef%bc%88%e5%90%ab%e6?ref=blog.skitisu.com)