Yigal BZ

Yigal BZ

  • 1.5k
  • 112
  • 6.6k

C# VS2017 WPF : fail to create draw movement on form

Feb 24 2020 2:52 PM
Hi
I am tryintg to draw a moving rectangle and circle on a form using the paint method.
A button should start the process. 2nd pres should end the program.
The once variable is a global boolean set to True on start.
X1 is a global int, set to 10 on start.
Up is a global boolean, set to true on start. 
 
Each iteeration the X1 variable is increased until 100, going down to 10, endlessly. 
 
Two problems:
1- No movement of the drawing on the form
2- No control on the form once the program starts.
 
 
  1. private void Form1_Paint(object sender, PaintEventArgs e)  
  2. {  
  3.       
  4.     Pen red = new Pen(Color.Red,3);  
  5.     Rectangle rect = new Rectangle(x1, x1, x1, x1);  
  6.     Rectangle circle = new Rectangle(x1+10, x1 + 10, x1 + 50, x1 + 50);  
  7.   
  8.     //Graphics g = e.Graphics;  
  9.     Graphics g = CreateGraphics();  
  10.     g.DrawRectangle(red,rect);  
  11.     g.DrawEllipse(red, circle);  
  12.   
  13.     red.Dispose();  
  14.     g.Dispose();             
  15. }  
  16.   
  17. private void button2_Click(object sender, EventArgs e)  
  18. {            
  19.     if (once)             
  20.         once = false;              
  21.     else  
  22.         Environment.Exit(0);  
  23.   
  24.     while (true)  
  25.     {  
  26.         if (up )  
  27.         {  
  28.             x1 += 10;  
  29.             if (x1 > 100)  
  30.                 up = false;  
  31.         }  
  32.         else  
  33.         {  
  34.             x1 -= 10;  
  35.             if (x1 <= 10)  
  36.                 up = true;  
  37.         }  
  38.         this.Invalidate();  
  39.         Thread.Sleep(500);  
  40.     }                      
  41. }  

Answers (4)