Why does this simple graphics not work

  • Thread starter Thread starter Tony Johansson
  • Start date Start date
T

Tony Johansson

Hello!

This code does not work when I have them in this event handler
private void Form1_Load(object sender, EventArgs e)
{
Graphics gr = this.CreateGraphics();
string text = "I'm the best!";
Font myFont = new Font("Arial", 14, FontStyle.Bold);
gr.DrawString(text, myFont, new SolidBrush(Color.Green), 10, 10);
}

But if I instead put the code lines into the event handler Form1_Paint it
works
private void Form1_Paint(object sender, PaintEventArgs e)
{
Graphics gr = e.Graphics; ;
string text = "I'm the best!";
Font myFont = new Font("Arial", 14, FontStyle.Bold);
gr.DrawString(text, myFont, new SolidBrush(Color.Green), 10, 10);
}

So why does it not work when I have the code lines in event handler
Form1_Load ?

//Tony
 
Jeff Johnson said:
I could've sworn I've sent you here before, but maybe it was someone else:
http://bobpowell.net/picturebox.htm

The site address that you posted doesn't tell why it's not possible to have
drawing code in the Form_Load or the constructor.
I hope someone know why this is not possible ?
private void Form1_Load(object sender, EventArgs e)
{
Graphics gr = this.CreateGraphics();
string text = "I'm the best!";
Font myFont = new Font("Arial", 14, FontStyle.Bold);
gr.DrawString(text, myFont, new SolidBrush(Color.Green), 10, 10);
}

//Tony
 
The site address that you posted doesn't tell why it's not possible to
have drawing code in the Form_Load or the constructor.
I hope someone know why this is not possible ?
private void Form1_Load(object sender, EventArgs e)
{
Graphics gr = this.CreateGraphics();
string text = "I'm the best!";
Font myFont = new Font("Arial", 14, FontStyle.Bold);
gr.DrawString(text, myFont, new SolidBrush(Color.Green), 10, 10);
}

The site tells you that arbitrarily calling CreateGraphics() is ALMOST
ALWAYS BAD.

Here's the short version: Do your screen drawing in the Paint event only.
EVER. The constructor is not the Paint event, so it's not a place for screen
drawing.
 
Back
Top