より洗練された例Console.SetCursorPosition()
を使用してカーソルを(可能であれば)左に移動し、Console.ReadKey()
を使用してキーを直接読み込み、バックスペースプレスを傍受し、キーを入力します:
0123あなたがもので、最後の型付きのリコールのための
LeftArrow
と
RightArrow
プレス、あるいは
UpArrow
プレスのためのサポートを追加したい場合は
using System;
using System.Linq;
namespace StackoverflowTests
{
class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Type the IP Address: ");
//Put the default IP address
var defaultIP = "192.168.0.190";
Console.Write(defaultIP);
string input = defaultIP;
//Loop through all the keys until an enter key
while (true)
{
//read a key
var key = Console.ReadKey(true);
//Was this is a newline?
if (key.Key == ConsoleKey.Enter)
{
Console.WriteLine();
break;
}
//Was is a backspace?
else if (key.Key == ConsoleKey.Backspace)
{
//Did we delete too much?
if (Console.CursorLeft == 0)
continue; //suppress
//Put the cursor on character back
Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop);
//Delete it with a space
Console.Write(" ");
//Put it back again
Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop);
//Delete the last char of the input
input = string.Join("", input.Take(input.Length - 1));
}
//Regular key? add it to the input
else if(char.IsLetterOrDigit(key.KeyChar))
{
input += key.KeyChar.ToString();
Console.Write(key.KeyChar);
} //else it must be another control code (ESC etc) or something.
}
Console.WriteLine("You entered: " + input);
Console.ReadLine();
}
}
}
は、さらに洗練され行うことができます。
私はそれが重複していると信じています:http://stackoverflow.com/questions/1655318/how-to-set-default-input-value-in-net-console-app – evilkos
頭に浮かんだ一つのアイデアは、キーボードを引っ掛けて自分でタイプをシミュレートすることができますが、何かが過剰なものになることがわかります。 – Abion47
通常の**簡単な**方法は、ユーザーが 'IPアドレス[192.168.1.1]:'を入力するような入力をした場合、デフォルトがどのようになるかを単に知らせることです。簡単に入力をシミュレートするか、エディターを自分で構築する必要があります。 –