Reputation: 117
I have the following code, which on key press, starts moving the two labels from top of the form to the bottom, and after reaching the bottom of the form, it stops. I have done it using the timer. Here is the code
private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
label1.Text = "Key Pressed: " + e.KeyChar;
//animate(sender, 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);
}
timer1.Stop();
}
Now during the animation (from the top of the form to the bottom), when I press the key, the animation restarts after reaching the bottom i.e. it completes the tick event and then and only then starts over or stop.
Now what I want is that whenever, during this movement of the labels from the top to bottom i.e. during the tick, if I press any key (or any specific key), the timer should stop.
In short, during the Timer1_Tick method, I want it to stop immediately on a key press.
I tried but couldn't get it to work. I hope that you folks here would help me sort this issue out and hope that you reply on your earliest. Thank you for your time!
Upvotes: 0
Views: 2730
Reputation: 754585
The problem here is that you are not really using the Timer
in the way that it's intended to be used. Ideally you would have an event that makes a change every time the tick event fires for a Timer
.
Here you listen to the event and do several rounds of processing without ever returning from the handler at which point you stop the timer. This means the code will only ever process the tick event once instead of N times.
To fix this try breaking up the handler to do incremental work once per tick and only stop once the drawing is complete. This will also allow you to handle key events in between the tick events and stop the timer. The best place to break up the work is at the Thread.Sleep
call (which itself should not appear in the handler)
Upvotes: 2
Reputation: 3573
First of all i recommend you to use keyDown and keyUp events instead of key press. To solve your problem: simple set a bool = true on keyDown and and the bool = false on keyUp. Now you can check the bool within you tick method and do whatever you want if you detect key is being pressed.
Upvotes: 0
Reputation: 5136
Try it is so simple
Public Boolean tick = false;
private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
tick = !tick;
label1.Text = "Key Pressed: " + e.KeyChar;
//animate(sender, e);
if(tick)
timer1.Start();
else
timer1.Stop();
}
Upvotes: 0