要實現(xiàn)輸入歷史記錄功能,可以通過保存用戶輸入的歷史記錄并在用戶按鍵盤向上或向下箭頭鍵時顯示相應(yīng)的歷史記錄。以下是一個簡單的示例代碼:
using System;
using System.Collections.Generic;
class Program
{
static List<string> history = new List<string>();
static int currentIndex = -1;
static void Main()
{
string input;
do
{
Console.Write("Enter a command: ");
input = ReadLineWithHistory();
if (!string.IsNullOrEmpty(input))
{
history.Add(input);
// 處理用戶輸入的命令
}
} while (input != "exit");
}
static string ReadLineWithHistory()
{
ConsoleKeyInfo key;
string input = "";
do
{
key = Console.ReadKey(true);
if (key.Key == ConsoleKey.Backspace)
{
if (input.Length > 0)
{
input = input.Remove(input.Length - 1);
Console.Write("\b \b");
}
}
else if (key.Key == ConsoleKey.Enter)
{
Console.WriteLine();
return input;
}
else if (key.Key == ConsoleKey.UpArrow)
{
currentIndex = Math.Max(0, currentIndex - 1);
if (currentIndex >= 0 && currentIndex < history.Count)
{
input = history[currentIndex];
Console.Write("\r" + new string(' ', Console.WindowWidth) + "\r");
Console.Write(input);
}
}
else if (key.Key == ConsoleKey.DownArrow)
{
currentIndex = Math.Min(history.Count - 1, currentIndex + 1);
if (currentIndex >= 0 && currentIndex < history.Count)
{
input = history[currentIndex];
Console.Write("\r" + new string(' ', Console.WindowWidth) + "\r");
Console.Write(input);
}
}
else
{
input += key.KeyChar;
Console.Write(key.KeyChar);
}
} while (true);
}
}
在這個示例代碼中,我們通過使用ConsoleKey.UpArrow
和ConsoleKey.DownArrow
來實現(xiàn)向上和向下箭頭鍵瀏覽歷史記錄,同時也實現(xiàn)了Backspace鍵刪除字符的功能。歷史記錄保存在history
列表中,currentIndex
用于記錄當前瀏覽到的歷史記錄的索引。當用戶按Enter鍵時,返回輸入的命令。
請注意,這只是一個簡單的實現(xiàn),您可能需要根據(jù)自己的需求進行修改和擴展。