我现在接受用户输入文件路径:
Console.WriteLine("Input file path");
string path = Console.ReadLine();
try
{
data = System.IO.File.ReadAllBytes(path);
}
catch
{
Console.WriteLine("Invalid file path entered");
System.Console.ReadKey();
return 1;
}
但是,如果用户输入错误的路径,他们将不得不再次输入整个内容。我意识到,当用户输入错误时,我的应用程序将立即退出,我可以再次询问,但是我仍然想让用户更轻松地完成此操作。
取而代之的是,我希望当用户在输入路径时使用Tab键时,该路径具有Windows命令行功能的自动完成功能。例如,如果我打开cmd并键入cd C:\win
并单击TAB,则cmd将找到C:\ Windows。
是否可以将该功能添加到控制台应用程序中以供用户输入?
起初,我认为清除特定的控制台行是不可行的,但是快速搜索显示,没有什么是不可能的。
因此,我创建了一个新的控制台应用程序,并开始考虑如何使类似的东西起作用。以下是“第一个工作草案”-我将独自[大量]重构它,然后将生成的代码放在Code Review上,但这应该足以使您入门。
该程序Tab使用字符串数组作为数据,使键自动完成当前输入,并与找到的第一项匹配;如果需要更智能的功能(例如,将当前文件夹的子路径作为数据,和/或在每次连续按下该Tab键时重复进行匹配操作),则必须对其进行一些调整:
class Program
{
static void Main(string[] args)
{
var data = new[]
{
"Bar",
"Barbec",
"Barbecue",
"Batman",
};
var builder = new StringBuilder();
var input = Console.ReadKey(intercept:true);
while (input.Key != ConsoleKey.Enter)
{
var currentInput = builder.ToString();
if (input.Key == ConsoleKey.Tab)
{
var match = data.FirstOrDefault(item => item != currentInput && item.StartsWith(currentInput, true, CultureInfo.InvariantCulture));
if (string.IsNullOrEmpty(match))
{
input = Console.ReadKey(intercept: true);
continue;
}
ClearCurrentLine();
builder.Clear();
Console.Write(match);
builder.Append(match);
}
else
{
if (input.Key == ConsoleKey.Backspace && currentInput.Length > 0)
{
builder.Remove(builder.Length - 1, 1);
ClearCurrentLine();
currentInput = currentInput.Remove(currentInput.Length - 1);
Console.Write(currentInput);
}
else
{
var key = input.KeyChar;
builder.Append(key);
Console.Write(key);
}
}
input = Console.ReadKey(intercept:true);
}
Console.Write(input.KeyChar);
}
/// <remarks>
/// https://stackoverflow.com/a/8946847/1188513
/// </remarks>>
private static void ClearCurrentLine()
{
var currentLine = Console.CursorTop;
Console.SetCursorPosition(0, Console.CursorTop);
Console.Write(new string(' ', Console.WindowWidth));
Console.SetCursorPosition(0, currentLine);
}
}
感谢您提出这个问题,这很有趣!
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句