Dong Lam Trien

Dong Lam Trien

  • 775
  • 968
  • 134.1k

Why does the Form_Paint event run continuously and only draw

Oct 22 2019 8:49 PM
I have the following code, I put a label in Form_Paint to track the number jump, I see the label jumping continuously but e.Graphics.DrawString(...) only looks once, does anyone know why ?
  1. public partial class Form1: Form {  
  2.  public Form1() {  
  3.   InitializeComponent();  
  4.   //progressBar1.Visible = false;  
  5.   progressBar1.Minimum = 0;  
  6.   progressBar1.Maximum = 100;  
  7.   this.Paint += new System.Windows.Forms.PaintEventHandler(this.Form1_Paint);  
  8.  }  
  9.  int iNum = 0;  
  10.  private void btnDrawText_Click(object sender, EventArgs e) //PaintEventArgs e  
  11.  {  
  12.   progressBar1.Value = 0;  
  13.   progressBar1.Visible = true;  
  14.   this.timer1.Interval = 100;  
  15.   this.timer1.Enabled = true;  
  16.   
  17.  }  
  18.  private void ShadowedTextPaint(PaintEventArgs e, int num) {  
  19.   using(Font font1 = new Font("Times New Roman", 250, FontStyle.Bold, GraphicsUnit.Pixel)) {  
  20.    PointF pointF1 = new PointF(310, 270);  
  21.    e.Graphics.DrawString(num.ToString(), font1, Brushes.LightGreen, pointF1);  
  22.    lblNum.Text = num.ToString();  
  23.   }  
  24.  }  
  25.  private void Form1_Paint(object sender, PaintEventArgs e) {  
  26.   ShadowedTextPaint(e, iNum);  
  27.  }  
  28.  private void timer1_Tick(object sender, EventArgs e) {  
  29.   if (progressBar1.Value < 100) {  
  30.    Random rd = new Random();  
  31.    iNum = rd.Next(0, 999);  
  32.    progressBar1.Value++;  
  33.   } else {  
  34.    this.timer1.Enabled = false;  
  35.    progressBar1.Visible = false;  
  36.   }  
  37.  }  
  38. }

Answers (6)