user4106887
user4106887

Reputation:

On key pressed multiple times

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?

Upvotes: 1

Views: 905

Answers (2)

Luke Marlin
Luke Marlin

Reputation: 1398

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.

Upvotes: 2

Jared Wadsworth
Jared Wadsworth

Reputation: 847

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

Upvotes: 0

Related Questions