
How to use the CreateGraphics method.The process of drawing on a Windows Forms application is managed by the Graphics object which is created during the Paint event. Internally, the system responds to the WM_PAINT message in the traditional manner by calling BeginPaint to obtain a device context, wrapping this device context with a managed Graphics class and passing this class to your drawing code in the PaintEventArgs which are provided first to the OnPaint protected method and then, in turn, to the Paint event. Generally, a correctly structured Windows Forms application or control should never need to obtain the Graphics object in any other way if the intention is to draw upon that object. Windows Forms controls and forms provide the CreateGraphics method specifically to enable you to access information about the graphics abilities of the system and perform simple tasks such as measuring text. This methods ease of use however, provides many opportunities for you to misuse the event driven structure of a Windows Forms application and consequently has undesirable side effects such as graphics that disappear or which appear incomplete. There are two cases in which inexperienced programmers consistently misuse the CreateGraphics method. They are:
Both of these methods can have serious consequences because, in the first instance the graphics provided to the paint event may not be the same as that provided by the CreateGraphics call. Specifically, in the case of double buffered controls or forms the Graphics object returned during the paint event refers to an in-memory bitmap and not to the Graphics object owned by the window. In the second instance, CreateGraphics is used most often in response to a button click or mouse event to asynchronously draw onto another control. This causes problems because at a later date the control will update itself and remove all of the carefully constructed output effectively erasing the desired graphics. The following table will provide you with guidelines on how to obtain the graphics object and what to do with it once you've got it.
|
|||||||||||||||||||||||||||||