Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CreateGraphics() Method and Paint Event Args

Tags:

c#

gdi+

I have read somewhere that CreateGraphics() will do this steps for us :

  1. BeginPaint
  2. Drawing
  3. EndPaint

I have my code like this :

private void Form1_Load(object sender, EventArgs e)
{
    grFrom = this.CreateGraphics();
    grFrom.FillRectangle(Brushes.Red, this.ClientRectangle);
}

There is no red rectangle...but, When I copy line below in Form1_paint, every thing runs correctly.

grFrom.FillRectangle(Brushes.Red, this.ClientRectangle);

So Question is Here: What is the e.Graphics in Form1_paint?

CreateGraphics or e.Graphics?

like image 343
S.A.Parkhid Avatar asked Mar 18 '11 13:03

S.A.Parkhid


People also ask

What is paint event in C#?

The Paint event is raised when the control is redrawn. It passes an instance of PaintEventArgs to the method(s) that handles the Paint event. When creating a new custom control or an inherited control with a different visual appearance, you must provide code to render the control by overriding the OnPaint method.

How many variables does CreateGraphics function has in the parameter list?

Parameter: This function accepts three parameters as mentioned above and described below: w: It is a number that sets the width of the off-screen graphics buffer.

What is graphic in C#?

Drawing in C# is achieved using the Graphics Object. The Graphics Object takes much of the pain out of graphics drawing by abstracting away all the problems of dealing with different display devices and screens resolutions. The C# programmer merely needs to create a Graphic Object and tell it what and where to draw.


1 Answers

Two things:

  1. CreateGraphics gives you a graphics object that you should always Dispose() prior to exiting. You should put your statement inside of a using block.
  2. The graphics you draw are only valid until the form gets repainted. In your case, by calling this in Form_Load, it's happening prior to the first render, and getting "thrown away". You should always put this in OnPaint() in order to have it "persistent" on the screen, as that will cause it to get redrawn when the control is redrawn.
like image 174
Reed Copsey Avatar answered Sep 24 '22 00:09

Reed Copsey