ITPub博客

首页 > IT职业 > IT职场 > C#读取控制台的输入字符串

C#读取控制台的输入字符串

IT职场 作者:foxsi 时间:2021-09-09 09:12:21 0 删除 编辑

问题:需要在控制台让用户输入,但是希望可以接受用户的多行输入,而不是有限制的一行。

解决方案:

static string acceptmultiLine()
{
ConsoleKeyInfo cki;
Console.TreatControlCAsInput = true;//防止Ctrl+C复制
Console.WriteLine("Press the F10 key to quit: n");
string result = string.Empty;
do
{
cki = Console.ReadKey();
result += cki.KeyChar;
if (cki.Key == ConsoleKey.Enter)
{
result += System.Environment.NewLine;//如果输入回车,则加入换行标志
}
} while (cki.Key != ConsoleKey.F10);//按F10退出
return result;
}

public static void Main(string[] args)
{
string s=acceptmultiLine();
Console.WriteLine(s);
Console.ReadLine();
}


修改后的代码:

static string acceptmultiLineChars2()
{
    ConsoleKeyInfo cki;
    Console.TreatControlCAsInput = true;//防止Ctrl+C复制
    Console.WriteLine("Press the CTRL+Enter key to quit: n");
    string result = string.Empty;
    do
    {
        cki = Console.ReadKey();
        if (cki.Key == ConsoleKey.Enter)
        {
            result += System.Environment.NewLine;//如果输入回车,则加入换行标志
            Console.SetCursorPosition(0, Console.CursorTop+1);//光标下移一行
        }
        result += cki.KeyChar;
    } while (cki.Key != ConsoleKey.Enter || (cki.Modifiers & ConsoleModifiers.Control) == 0);//按Ctrl+Enter退出
    return result;
}

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/4201/viewspace-2800517/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-08-12

  • 博文量
    74
  • 访问量
    523