这是一个概念验证,可让您使用任何字符序列集合。我假设您只匹配字符(而不是其他键,例如 Keys.Left)。
// Initialize the collection of strings to be matched against here.
string[] stringSequences = new string[] { "yes", "no", "hello" };
int maxLength = stringSequences.Max(s => s.Length);
// The buffer to hold the sequence of the last N characters.
string buffer = "";
while (true)
{
// Read the next character, and append it to the end of the buffer.
ConsoleKeyInfo next = Console.ReadKey();
buffer += next.KeyChar;
// If the buffer has exceeded our maximum length,
// trim characters from its start.
if (buffer.Length > maxLength)
buffer = buffer.Substring(1);
// Check whether the last n characters of the buffer
// correspond to any of the sequences.
string match = stringSequences.FirstOrDefault(s => buffer.EndsWith(s));
if (match != null)
{
// Match! Perform any custom processing here.
Console.WriteLine(Environment.NewLine + "Match: " + match);
}
}
编辑:适用于按键。
我无法轻松地针对 Keys 进行测试,因此我改用了 ConsoleKey;不过,翻译代码应该不会太难。
// Initialize the collection of key sequences to be matched against here.
ConsoleKey[][] keysSequences = new ConsoleKey[][]
{
new ConsoleKey[] { ConsoleKey.Y, ConsoleKey.E, ConsoleKey.S },
new ConsoleKey[] { ConsoleKey.N, ConsoleKey.O },
new ConsoleKey[] { ConsoleKey.H, ConsoleKey.E, ConsoleKey.L, ConsoleKey.L, ConsoleKey.O },
};
int maxLength = keysSequences.Max(ks => ks.Length);
// The buffer to hold the sequence of the last N keys.
List<ConsoleKey> buffer = new List<ConsoleKey>();
while (true)
{
// Read the next key, and append it to the end of the buffer.
ConsoleKeyInfo next = Console.ReadKey();
buffer.Add(next.Key);
// If the buffer has exceeded our maximum length,
// trim keys from its start.
if (buffer.Count > maxLength)
buffer.RemoveAt(0);
// Check whether the last n keys of the buffer
// correspond to any of the sequences.
ConsoleKey[] match = keysSequences.FirstOrDefault(ks =>
buffer.Skip(buffer.Count - ks.Length).SequenceEqual(ks));
if (match != null)
{
// Match! Perform any custom processing here.
Console.WriteLine(Environment.NewLine + "Match: " +
string.Concat(match.Select(k => k.ToString()).ToArray()));
}
}