Reputation: 546
i tried to draw some boxes right after form is Initialized
however they didn't appeared.
i put the code under the InitializeComponent();
like this
public Form2()
{ InitializeComponent();
System.Drawing.SolidBrush myBrush = new System.Drawing.SolidBrush(System.Drawing.Color.LimeGreen);
System.Drawing.Graphics formGraphics = this.CreateGraphics();
formGraphics.FillRectangle(myBrush, new Rectangle(0, 0, 200, 300)); }
but when i drew them after the form is initialized they worked!
So i thought i should wait a moment and draw the boxes.
Then i put the thread to make the draw function wait for 10ms
In short i modified the code like this
public Form2()
{
InitializeComponent();
Thread t1 = new Thread(new ThreadStart(Run));
t1.Start();
}
void Run()
{
Thread.Sleep(10);
System.Drawing.SolidBrush myBrush = new System.Drawing.SolidBrush(System.Drawing.Color.LimeGreen);
System.Drawing.Graphics formGraphics = this.CreateGraphics();
formGraphics.FillRectangle(myBrush, new Rectangle(0, 0, 200, 300));
}
and i succeed
So my question is why i have to wait for a moment to draw something right after the form is initialized?
and is there any way to solve this problem not using thread?
Upvotes: 1
Views: 1296
Reputation: 546
using paint event works plus don't use CreateGraphics instead use e.Graphics
Upvotes: 0
Reputation: 675
I find your question interesting and did some experiments myself. I managed to get it to work in Form1_Paint callback :)
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.Paint += new System.Windows.Forms.PaintEventHandler(this.Form1_Paint);
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
System.Drawing.SolidBrush myBrush = new System.Drawing.SolidBrush(System.Drawing.Color.LimeGreen);
System.Drawing.Graphics formGraphics = e.Graphics; //this.CreateGraphics();
formGraphics.FillRectangle(myBrush, new Rectangle(0, 0, 200, 300));
}
}
Edit: Edited based on Idle_Mind's comment
Upvotes: 1