1. Drawing to the screen
Bool drawellipse = false;
Void drawellipsebutton_click (Object sender, eventargs e ){
Drawellipse =! Drawellipse;
Graphics G = This. creategraphics ();
Try {
If (drawellipse ){
// Draw the ellipse
G. fillellipse (brushes. darkblue, this. clientrectangle );
}
Else {
// Erase the previusly drawn Ellipse
G. fillellipse (systembrushes. Control, this. clientrectangle );
}
}
Finally {
G. Dispose ();
}
}
Note: The reason for adding a try-Catch Block is: "The graphic class's implementation of idisposable dispose can release the underlying graphics object that it's maintaining. the graphics object must be released. Here, you can also use the C # unique using block (dispose is automatically called after completion ):
Void drawellipsebutton_click (Object sender, eventargs e ){
Using (Graphics G = This. creategraphics ()){
If (drawellipse)
G. fillellipse (brushes. darkblue, this. clientrectangle );
Else
G. fillellipse (systembrushes. Control, this. clientrectangle );
} // G. Dispose called automatically here
}
Note: If you want to enable automatic re-painting of an ellipse during window resize. This must be added to the constructor of the Form class. setstyle (controlstyles. resizeredraw, true); add this to the button click event. refresh (); (equivalent to this. invalidate (true) plus this. update ();) but it is inefficient to automatically redraw all windows during resize, which is time-consuming.
2. Saving and restoring graphics settings
Use the graphicsstate object in system. Drawing. drawing2d namespace, and add the SAVE () and restore () Methods of the graphics class.
Void drawsomething (Graphics g ){
// Save the old
Graphicsstate oldstate = G. Save ();
// Change the smooth Mode
G. smoothingmode = smoothingmode. antialias;
// Start painting
// Restore the old
G. Restore (oldstate );
}