Skip to content

Instantly share code, notes, and snippets.

@earlgreyxxx
Created November 1, 2020 10:31
Show Gist options
  • Save earlgreyxxx/91de85377f650e68640f7f46410cf598 to your computer and use it in GitHub Desktop.
Save earlgreyxxx/91de85377f650e68640f7f46410cf598 to your computer and use it in GitHub Desktop.
/// <summary>
/// コンソール関連のヘルパー&ラッパー関数など。C#4.0必須
/// </summary>
public static class ConsoleEx
{
/// <summary>
/// メッセージを出力してキー入力を待機します。
/// </summary>
public static ConsoleKeyInfo WriteLineAndReadKey(string msg = "\n何かキーを押してください。",bool echoback = false)
{
Console.WriteLine(msg);
return Console.ReadKey(echoback);
}
public static string WriteAndReadLine(string mesg,bool intercept = false)
{
if(!string.IsNullOrEmpty(mesg))
Console.Write(mesg);
return ReadLine(intercept);
}
/// <summary>
/// エコーバック無しにキー入力を行う。(たぶん日本語はだめ)
/// </summary>
/// <returns>入力値</returns>
public static string ReadLine(bool intercept,char mask = '*')
{
if(!intercept)
return Console.ReadLine();
var cs = new List<char>();
bool isContinue = true;
while(isContinue)
{
var ki = Console.ReadKey(true);
switch(ki.Key)
{
case ConsoleKey.Escape:
cs.Clear();
goto case ConsoleKey.Enter;
case ConsoleKey.Enter:
isContinue = false;
break;
case ConsoleKey.Backspace:
if(cs.Count > 0)
{
cs.RemoveAt(cs.Count - 1);
Console.Write("\b \b");
}
break;
default:
if(ki.KeyChar != '\0')
cs.Add(ki.KeyChar);
Console.Write(mask);
break;
}
}
return new string(cs.ToArray());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment