CreateGraphics() Method and Paint Event Args
I have read somewhere that CreateGraphics()
will do this steps for us :
- BeginPaint
- Drawing
- 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:
- CreateGraphics gives you a graphics object that you should always
Dispose()
prior to exiting. You should put your statement inside of a using block. - 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.
精彩评论