2

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.

Ryan Peschel
  • 11,087
  • 19
  • 74
  • 136
  • Could you give a bit more info about what you are trying to do? Can't you use the keydown events? – Oskar Kjellin Oct 21 '12 at 19:58
  • @OskarKjellin: Yeah but I want to make a custom function that behaves identically to `KeyDown` except with the additional condition that an arbitrary delay has passed since it last returned true for that key. – Ryan Peschel Oct 21 '12 at 19:59
  • What I meant is, can't you just subscribe to those events and then perform your logic on up / down – Oskar Kjellin Oct 21 '12 at 20:05
  • check this so post http://stackoverflow.com/questions/709540/capture-multiple-key-downs-in-c-sharp – Prabhu Murthy Oct 21 '12 at 20:06

1 Answers1

1

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;
}
Majid Max
  • 509
  • 1
  • 4
  • 10