如何编写一个函数来确定密钥是否已关闭且延迟是否已通过?

时间:2012-10-21 19:55:16

标签: c# refactoring key stopwatch

我现在有一个看起来像这样的功能:

public static bool IsKeyDownWithDelayPassed(Keys key, int delay)
{
    bool timeElapsed = stopWatch.ElapsedMilliseconds > delay;

    bool isKeyDown = currentKeyboardState.IsKeyDown(key);

    if (timeElapsed && isKeyDown)
    {
        stopWatch.Restart();
    }

    return timeElapsed && isKeyDown;
}

这完美无缺,但一次只能使用一个键。例如,如果我想使用箭头键并进行对角线移动(同时按住向下和向下箭头键),则它不起作用。

我想到了一个涉及Dictionary映射KeysStopwatch的解决方案,但这似乎有点过于复杂。我错过了可以简化这项任务的东西吗?

感谢。

1 个答案:

答案 0 :(得分:1)

使用它:

Dictionary<Keys, DateTime> keytimes = new Dictionary<Keys, DateTime>();

public bool IsKeyDownWithDelayPassed(Keys key, long delay)
{
    if(!keytimes.Keys.Contains(key) || keytimes[key] == DateTime.MinValue)
        return false;
    long elapsed = DateTime.Now.Ticks - keytimes[key].Ticks;    
    return delay < elapsed;
}

private void KeyDownEvent(object sender, KeyEventArgs e)
{
    keytimes[e.KeyData] = DateTime.Now;
}

private void KeyUpEvent(object sender, KeyEventArgs e)
{
    keytimes[e.KeyData] = DateTime.MinValue;
}