1
votes

I need to make different commands on Escape key pressed, for example

if Escape key is once pressed .. Draw(250,250);
if Escape key is twice pressed .. Draw(350,350);
if Escape key is triple pressed .. Draw(450,450);

on one key I have to have multiple different commands, how to make the app to count how many times a key is pressed and using that info .. to run a specific code?

2

2 Answers

2
votes

You should create a counter and increment it each time the key is pressed. If you are talking about double or triple "clicking", you also need to set a Timer. Each time the timer ends, you reset your counter.

Only thing left is to call the method you want depending on your counter value.

int MyKeyCounter = 0;
Timer CounterResetter = new Timer(1000);
CounterResetter.Elapsed += ResetCounter;

void OnKeyPressEvent(object sender, KeyPressEventArgs e)
{
    if (e.Key == Key.Escape)
    {
        MyKeyCounter++;
        if(!CounterResetter.Enabled)
            CounterResetter.Start();
    }
}

void ResetCounter(Object source, ElapsedEventArgs e)
{
    if(MyKeyCounter == 1)
        Method1();
    else if (MyKeyCounter == 2)
        Method2();
    ...

    MyKeyCounter = 0;
}

Attach the event on the control you want and put the fields at the top.

0
votes

This is the best way I can think of. It waits for the user to input a key, and counts it if its the escape key. Any other key pressed breaks the loop, then you count the times pressed!

        ConsoleKeyInfo key;
        int timesPressed = 0;
        while(true) {
            key = Console.ReadKey();
            if (!key.Equals( ConsoleKey.Escape ) || timesPressed >= 3) {
                break;
            }
            timesPressed++;
        }