Click here to Skip to main content
15,892,809 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello!
I'm trying to make a program: object moves forward while a button press and when you let go it stops.I can't understand how to make it. Can anybody help me?

What I have tried:

C#
private void button1_Click(object sender, EventArgs e)
       {
           for (int i = 1; i < 300; i++)
           {
               int x2 = i + 1;
               int y2 = 100;
               Graphics g2 = this.CreateGraphics();
               g2.FillRectangle(new SolidBrush(Color.Black), x2, y2, 6, 6);
               Invalidate();

               int x1 = i-1;
               int y1 = 100;
               Color c = this.BackColor;
               Graphics g1 = this.CreateGraphics();
               g1.FillRectangle(new SolidBrush(c), x1, y1, 6, 6);


               System.Threading.Thread.Sleep(50);


           }
       }
Posted
Updated 9-Oct-16 1:49am

1 solution

Stop using Thread.Sleep: that causes your whole thread - in this case the UI thread, which dos all the work of handling the display and all user input - to be suspended.
And even if it wasn't, that code is a loop inside a Click event handler.
Which means that the screen doesn't get updated and mouse clicks don't work until you leave the method!

Throw away the loop - Windows in general and C# in particular don't work like that outside of console applications.
Add a Timer to your form. Set the Interval property to 100 and start it.
Add a class level bool called "moving" and start if as false.
In your Button click event, invert the start of your "moving" variable.
Handle the Tick event for the timer.
In the handler, check "moving". If it's true, do your code inside the loop once, and once only. )This will mean moving i to class level as well. If it's false, do nothing.

BTW: That's not the best way to do the job, and it's actually dangerous. For the moment, at the end of any method, call Dispose on all the Graphics items you created:
C#
g1.Dispose();
g2.Dispose();
If you don't, your application will crash sooner than you think...
There are betters ways, such as doing the drawing code in the Form Paint event, but that's for later, I suspect.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900