How to: Draw a Filled Rectangle on a Windows Form
This example draws a filled rectangle on a form.
Example
Dim myBrush As New System.Drawing.SolidBrush(System.Drawing.Color.Red)
Dim formGraphics As System.Drawing.Graphics
formGraphics = Me.CreateGraphics()
formGraphics.FillRectangle(myBrush, New Rectangle(0, 0, 200, 300))
myBrush.Dispose()
formGraphics.Dispose()
System.Drawing.SolidBrush myBrush = new System.Drawing.SolidBrush(System.Drawing.Color.Red);
System.Drawing.Graphics formGraphics;
formGraphics = this.CreateGraphics();
formGraphics.FillRectangle(myBrush, new Rectangle(0, 0, 200, 300));
myBrush.Dispose();
formGraphics.Dispose();
System::Drawing::SolidBrush^ myBrush =
gcnew System::Drawing::SolidBrush(System::Drawing::Color::Red);
System::Drawing::Graphics^ formGraphics;
formGraphics = this->CreateGraphics();
formGraphics->FillRectangle(myBrush, Rectangle(0, 0, 200, 300));
delete myBrush;
delete formGraphics;
Compiling the Code
You cannot call this method in the Load event handler. The drawn content will not be redrawn if the form is resized or obscured by another form. To make your content automatically repaint, you should override the OnPaint method.
Robust Programming
You should always call Dispose on any objects that consume system resources, such as Brush and Graphics objects.
See Also
Reference
Concepts
Brushes and Filled Shapes in GDI+
Other Resources
Getting Started with Graphics Programming
Graphics and Drawing in Windows Forms
Using a Pen to Draw Lines and Shapes