编辑以允许用户进行编辑
Console.Write("Type the IP Address:\n");
SendKeys.SendWait("192.168.1.1"); //192.168.1.1 text will be editable :)
strIpAddress=Console.ReadLine();
System.Windows.Forms
添加到引用并添加命名空间。如果这是 IP 地址,请按回车键。如果不是,请自行输入然后按回车键!
;-) - Shamim以下是一个更复杂的示例,使用Console.SetCursorPosition()
将光标向左移动(如果可能),并使用Console.ReadKey()
直接读取按键以拦截退格键和回车键:
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();
}
}
}
else if(char.IsLetterOrDigit(key.KeyChar))
来捕获这些键,我一开始没有做这个是我的错。 - Maximilian Gerhardt