PFlem.com SudokuSharp
a C# learning space

Buy me a cup of coffee?

Painting the Form

GDI+

Graphic Device Interface (GDI) is the default method used to paint a graphical user interface. GDI+ is the new and improved version. It is used to draw lines, paint with shapes brushes, and display text.

In order to use the GDI+ objects, you will need to include the code using System.Drawing;. And I like to include the code using System.Drawing.Drawing2D; as well.

To paint on the form you want to instanciate a Graphics object. Below the Graphics object is simply called "g" and it is set to e.Graphics; "e" being the Paint Event arguments that are passed to the OnPaint method.

protected override void OnPaint(PaintEventArgs e)
{
   // Creating Graphics allows drawing on the form
   Graphics g = e.Graphics; }

Let's use that graphics object we just created and use one of its methods to draw a line on the Form. Here we are using a black pen to draw the line from the origin of the form, which is the upper left corner to the point that is 150 pixels to the right and 250 pixels down.

g.DrawLine(Pens.Black, 0, 0, 150, 250);

Now, let's draw a rectangle to box in our line we just drew.

g.DrawRectangle(Pens.Black, 0, 0, 150, 250);

You can probably guess that the following code fills a rectangle with the color black. The first two numbers designate the beginning point on the form where the rectangle begins. The next two numbers are the size of the rectange by width and height. So the result is a black rectangle (or in this case a square) that is 50 pixels wide and 50 pixels tall located in the upper left corner.

g.FillRectangle(Brushes.Black, 0, 0, 50, 50);

Next let's put some text on the form. Here our old friend, Hello World, makes an appearance starting at the point at 10 pixels to the right and 10 pixels down from the upper left corner.

g.DrawString("Hello World", new Font("Arial", 16), Brushes.Green, 10, 10);

As you can see it gets kind of wordy having to use the new Font() every time you want to write something. To avoid all that typing it's best to define some Pens, Brushes, Fonts, and even some colors that you will be using.

Color clrBlack = Color.Black;
Pen penThickBlack = new Pen(Color.Black, 2);
SolidBrush brshBlack = new SolidBrush(clrBlack);
Font fntArialTiny = new Font("Arial Rounded MT Bold", 10, FontStyle.Regular);

Defining your Pens and Brushes and such is very helpful and cuts down on the amount of code you have to type. I find it easier to read as well. Especially, when you use a good naming convention such as penThickBlack. It's descriptive and tells you exactly what it is.