Waqas Abdullah

Waqas Abdullah

  • NA
  • 1
  • 2.8k

How to listen to Key Event in Timer

Jan 19 2014 5:55 AM

Hello everybody,

 I am creating this game in C# in which English alphabets (in the form of labels) fall from the top of the form to the bottom and I have to press the corresponding letter on the keyboard to score. I have used a timer, for now, to move two labels from top to bottom and I have used KeyUp and KeyDown events. The problem is to associate the key event with the timer.

 
In short, I want the code to do something as soon as the user presses any key during the timer. But when I press the key, it first completes the timer and then and only then does something. I want the timer to stop or do something immediately the user presses any key.
 
Here is my code:
 
  private void Form1_Load(object sender, EventArgs e)
        {
            timer1.Start();
        }
 
 private void timer1_Tick(object sender, EventArgs e)
        {
            Random random = new Random();
            int X = random.Next(0, 1230);
            int y = X;
            label2.Location = new Point(X, 5);
            label3.Location = new Point(X + 20, 5 + 20);
            for (int i = 5; i <= 470; i++)
            {
                label2.Location = new Point(y, i);
                label3.Location = new Point(y + 20, i + 20);
                Thread.Sleep(1);
            }
        }
 
      
        static bool pressed = false;
        private void Form1_KeyUp(object sender, KeyEventArgs e)
        {
            pressed = false;
        }
        private void Form1_KeyDown(object sender, KeyEventArgs e)
        {
            pressed = true;
            label1.Text = "Key Pressed: " + e.KeyCode;
            //animate(sender, e
            //timer1.Start();
        }
    }
 
I look forward to help. Thanks! 

Answers (1)