Search code examples
c#refactoringkeystopwatch

How to write a function that determines if a key is down and a delay passed?


I have a function that looks like this right now:

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;
}

This works perfectly but it only works with one key at a time. For example, if I want to use the arrow keys and do diagonal movement (right and down arrow keys held down at same time), it doesn't work.

I thought of a solution that involved a Dictionary that mapped Keys to Stopwatches but that seemed a bit overly complex. Am I missing something that could simplify this task?

Thanks.


Solution

  • use this:

    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;
    }