2014-08-28 46 views
0

我的目的是在表单应用程序中每秒更改渐变线条。但它不起作用。 valueble计数器“改变的标签,但在形式上油漆不改变..我的变量没有改变,因为它应该是

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Windows.Forms; 

namespace WindowsFormsApplication1 
{ 
    public partial class Form1 : Form 
    { 
     public Form1() 
     { 
      InitializeComponent(); 
     } 

     private int counter = 1; 

     private void timer1_Tick(object sender, EventArgs e) 
     { 
      counter++; 
      if (counter >= 10) 
       timer1.Stop(); 
      lblCountDown.Text = counter.ToString(); 
     } 

     private void button1_Click(object sender, EventArgs e) 
     { 
      counter = 0; 

      timer1.Tick += new EventHandler(timer1_Tick); 
      counter = new int(); 

      timer1.Interval = 1000; // 1 second 
      timer1.Start(); 
      lblCountDown.Text = counter.ToString(); 
     } 
     private void Form1_Paint(object sender, PaintEventArgs e) 
     { 
      e.Graphics.DrawLine(new Pen(Brushes.Crimson),200,200,counter ,300) ; 
     } 
    } 
} 

我打算改变我的画梯度时间,但变量没有被改变时,其

来形成油漆...但它如果U可以家伙在LBL不会改变......

帮助我。不知道该怎么办。

+0

您需要重画的形式,如果调整/在任何时候其执行并行变换过程中移动的形式? – Sayse 2014-08-28 08:31:34

+0

添加'Invalidate(); 'timer1_Tick'中的Update();'重新绘制表格 – 2014-08-28 08:32:18

+0

为什么你有'private int counter = 1;'counter = 0;''和counter = new int();'。这不是太多吗?我认为'私人int计数器= 0;''计数器= 0;'会没事的。 – 2014-08-28 08:34:41

回答

1

这里,这一个工程,答案是对的形式调用this.Invalidate()每一个时钟滴答。

public partial class Form1 : Form 
{ 
    int counter = 0; 

    public Form1() 
    { 
     InitializeComponent(); 

     timer1.Tick += new EventHandler(timer1_Tick); 
    } 

    private void button1_Click(object sender, EventArgs e) 
    { 
     counter = 1; 
     timer1.Interval = 1000; // 1 second 
     timer1.Start(); 
     lblCountDown.Text = counter.ToString(); 
    } 

    private void timer1_Tick(object sender, EventArgs e) 
    { 
     counter++; 
     if (counter >= 10) 
      timer1.Stop(); 
     lblCountDown.Text = counter.ToString(); 
     this.Invalidate(); 
    } 

    private void Form1_Paint(object sender, PaintEventArgs e) 
    { 
     e.Graphics.DrawLine(new Pen(Brushes.Crimson), 200, 200, counter*10, 300); 
    } 
} 

也改变了几件事情:

  1. 事件处理只设置一次 - 避免多个处理程序,如果用户点击按钮几次。
  2. 删除counter = new int() - 不需要,您已将其设置为= 1。
  3. 在Form1_Paint中,将x2坐标设置为计数器* 10,以便更容易看到移动。
0

我会建议如下:

  1. 使用Panel控制绘制及其漆事件例如Panel_Paint
  2. Timer_Tick使用Panel.Invalidate();
  3. 在油漆事件处置用于图形对象,它是Pen

在窗体中添加名为panel1的面板控件。 保持面板外的其他所有控件。

面板的实例涂料和定时器事件

private void panel1_Paint(object sender, PaintEventArgs e) 
    { 
    using (Pen pen = new Pen(Brushes.Crimson)) 
     { 
      e.Graphics.DrawLine(pen, 200, 200, counter, 300);     
     } 
    } 

private void timer1_Tick(object sender, EventArgs e) 
    {    
     counter++; 
     if (counter >= 10) 
      timer1.Stop(); 
     lblCountDown.Text = counter.ToString(); 
     panel1.Invalidate();   
    } 
相关问题