2

我现在有一个看起来像这样的函数:

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映射KeysStopwatches 的解决方案,但这似乎有点过于复杂。我是否遗漏了可以简化此任务的内容?

谢谢。

4

1 回答 1

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;
}
于 2012-10-21T20:47:06.143 回答