使用绘画方法在表格上创建运动 - 不起作用

Using paint method to create movement on form - not working

我正在尝试使用 paint 方法在窗体上绘制移动的矩形和圆形。 一个按钮应该开始这个过程。第二次按下应结束程序。 once 变量是一个全局布尔值,在开始时设置为 True。 X1 是一个全局 int,在开始时设置为 10。 Up 是一个全局布尔值,在开始时设置为 true。

每次迭代,X1 变量都会增加到 100,然后一直下降到 10。

我观察到以下两个问题。

  1. 表格上的绘图没有移动
  2. 程序启动后无法控制表单

代码如下:

private void Form1_Paint(object sender, PaintEventArgs e)  
{  

    Pen red = new Pen(Color.Red,3);  
    Rectangle rect = new Rectangle(x1, x1, x1, x1);  
    Rectangle circle = new Rectangle(x1+10, x1 + 10, x1 + 50, x1 + 50);  

    //Graphics g = e.Graphics;  
    Graphics g = CreateGraphics();  
    g.DrawRectangle(red,rect);  
    g.DrawEllipse(red, circle);  

    red.Dispose();  
    g.Dispose();             
}  

private void button2_Click(object sender, EventArgs e)  
{            
    if (once)             
        once = false;              
    else  
        Environment.Exit(0);  

    while (true)  
    {  
        if (up )  
        {  
            x1 += 10;  
            if (x1 > 100)  
                up = false;  
        }  
        else  
        {  
            x1 -= 10;  
            if (x1 <= 10)  
                up = true;  
        }  
        this.Invalidate();  
        Thread.Sleep(500);  
    }                      
}  

这是使用 System.Windows.Forms.Timer 完成此任务的一种方法,请查看更改和评论:

private int x1 = 4;
System.Windows.Forms.Timer timer;
private bool once = true;
private bool up = false;
private void Form1_Paint(object sender, PaintEventArgs e)
{
    // use e.Graphics
    Graphics g = e.Graphics;
    Pen red = new Pen(Color.Red, 3);
    Rectangle rect = new Rectangle(x1, x1, x1, x1);
    Rectangle circle = new Rectangle(x1 + 10, x1 + 10, x1 + 50, x1 + 50);
    g.DrawRectangle(red, rect);
    g.DrawEllipse(red, circle);

    red.Dispose();
    g.Dispose();
}

private void button2_Click(object sender, EventArgs e)
{
    if (once)
    {
        once = false;
        Init();
    }
    else
    {
        if (timer != null)
        {
            timer.Stop();
            timer.Dispose();
            timer = null;
        }
        // you can exit app...
         Application.Exit();
    }
}

private void Init()
{
    if (timer == null)
    {
        timer = new Timer();
        timer.Interval = 500;
        timer.Tick += timer_tick;
    }

    timer.Start();
}

private void timer_tick(object sender, EventArgs e)
{
    if (up)
    {
        x1 += 10;
        if (x1 > 100)
            up = false;
    }
    else
    {
        x1 -= 10;
        if (x1 <= 10)
            up = true;
    }
    this.Invalidate();
}