加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 存储最后N次击键

发布时间:2020-12-15 21:30:10 所属栏目:百科 来源:网络整理
导读:在这里做什么我有点不知所措.我希望某些键击序列执行某些操作. 我基本上需要存储最后N次击键,当按下某个键时,查找与最近的击键相匹配的序列. 所以说我有2个序列: yesno 当我输入时,我的击键历史如下所示: aababcabcnabcno 此时它应识别序列号并执行适当的
在这里做什么我有点不知所措.我希望某些键击序列执行某些操作.

我基本上需要存储最后N次击键,当按下某个键时,查找与最近的击键相匹配的序列.

所以说我有2个序列:

yes
no

当我输入时,我的击键历史如下所示:

a
ab
abc
abcn
abcno

此时它应识别序列号并执行适当的操作.

它还需要使用以下序列:

year
yell

和输入如:

yeayell

密钥序列具有有限长度,因此可以使用类似循环缓冲区的东西丢弃旧的击键,在这种情况下,最佳大小为3.

我的击键用Keys枚号表示.

我应该使用哪些数据结构或算法来存储最后N次击键并在最后找到序列?

解决方法

这是一个概念验证,允许您使用任何字符序列集合.我假设你只匹配字符(而不是其他键,如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.L,};
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()));
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读