开发者

CreateGraphics() Method and Paint Event Args

开发者 https://www.devze.com 2023-02-18 19:00 出处:网络
I have read somewhere that CreateGraphics() will do this steps for us : BeginPaint Drawing EndPaint I have my code like this:

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?


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.


Your form load call is drawing to the form, but then the first regular form paint event writes over it, so you never see it. (As this happens before your presented the form at all)

So Question is Here : What is the

e.Graphics in form1_paint ?

CreateGraphics or e.Graphics ?

I'm fairly sure the are equivilent, what you need is a better understanding of the windows forms event lifecycle.

This answer has relevant links: WinForms event life cycle


You are creating a new graphics object, which is most likely backed by a memory buffer. The Graphics objects you get from e.Graphics is backed by a buffer which represents the screen area by the current window (window as in Window Handle, not a window with title bar, etc).

You can always bit blit the data from a created graphics object onto the one from e.Graphics.

I am sure someone will elaborate much more than I have.

0

精彩评论

暂无评论...
验证码 换一张
取 消