I have written an event handler method and attached it to the Paint
event of a Form
(just the main window). This event sends a PaintEventArgs
You .NET WinForms kids really should learn the Win32 API. Pick up a copy of Petzold already!
Why does g1 redraw the image in the whole window, while g2 only draws the new portion, even if I call g2.Clear() before drawing?
Presumably g2
is a wrapper around a device context received from BeginPaint. I imagine WinForms wraps PAINTSTRUCT::rcPaint for you - this variable describes the area to be painted. This is expected behaviour - rather than burning CPU cycles redrawing your entire window every single time another window overlaps it by just one pixel, you can redraw ... just the one pixel!
g2.Clear
is presumably limited by rcPaint
.
g1
is probably a GetDC
for the window - which gives you the entire surface to draw on.
Why, with either Graphics object, is the image only redrawn when the window increases in size, and not when it is made smaller?
The underlying window class probably doesn't have CS_HREDRAW
or CS_VREDRAW
window styles. Without these, there's no reason for the default behaviour to request you redraw the window when it gets smaller: Windows knows what the entire window looks like, it can clip the unwanted bits away. This is unlike when the window gets bigger, it doesn't know what to draw in the new area.
If PaintEventArgs.Graphics can (or should) not be used for drawing, what is it used for? I would imagine it just prevents you from having to create a new Graphics instance if the form doesn't need to be redrawn; is there more to it that I'm missing?
It's used for drawing. Unless you have some complex drawing requirements, you can use the PaintEventArgs.Graphics
minimize the amount of painting that goes on to your window. (As above - this is a huge saver of CPU cycles and it's probably a simple wrapper over BeginPaint
and EndPaint
- which is how drawing to the client area is meant to be done.)