这是包含方法,它写入隐藏的字母。当我按下退格键时,我需要以某种方式从控制台中删除 char *。

    private static string Password()
    {
        bool enter=true;
        string pass="";
        do
        {

            char letter = Console.ReadKey(true).KeyChar;
            if (letter == (char)13)
            { enter = false; }
            else if (letter == (char)8 && pass.Length >= 1)
            {
                pass = pass.Remove(pass.Length - 1);
                Console.Write("\b");
            }
            else
            {
                pass += letter;
                Console.Write("*");
            }
        } while (enter);
        Console.WriteLine();
        return pass;
    }

我搜索了一个答案,但命令 Console.Write("\b");但它似乎无法正常工作。

最佳答案

您可以将光标的位置设置回 1,写入一个空字符,然后再将其移回。像这样:

private static string Password()
{
    bool enter = true;
    string pass = "";
    do
    {
        char letter = Console.ReadKey(true).KeyChar;
        if (letter == (char)13)
        { enter = false; }
        else if (letter == (char)8 && pass.Length >= 1)
        {
            pass = pass.Remove(pass.Length - 1);
            Console.CursorLeft--;
            Console.Write('\0');
            Console.CursorLeft--;
        }
        //Additionally, don't print backspaces if it's the first character.
        else if (letter != (char)8)
        {
            pass += letter;
            Console.Write("*");
        }
    } while (enter);
    Console.WriteLine();
    return pass;
}

关于c# - 如何从控制台窗口中删除 char '*'?命令 Console.Write ("\b");没用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20409026/

10-17 02:38