Device Contexts

Introduction to GDI

Most operating systems nowadays are graphics-oriented, and sometimes graphics-intensive, including Microsoft Windows. Such operating systems use shapes, pictures, lines, colors, and various types of options to convey the impression of physical objects. When we stare at a flat screen built in front of a monitor filled with insignificant wires, we believe that we are looking at physical buildings or real people. This is done through smart and effective representations that have made computer use nowadays become fun and useful.

To support the ability to represent pictures and other visual features, the .NET Framework provides various classes created in many namespaces.

Practical LearningPractical Learning: Introducing Graphical Applications

  1. Start Microsoft Visual Studio 2022

    Create New Project

  2. In the Visual Studio 2022 dialog box, click Create a New Project
  3. In the Create a New Project wizard page, in the languages combo box, select C#

    Create New Project

  4. In the list of the projects templates, click Windows Forms App
  5. Click Next
  6. In the Configure Your New Project dialog box, change the project Name to Exercise1
    Accept or change the project Location
  7. Click Next
  8. In the Framework combo box, select the highest version: .NET 8.0 (Long Term Support)
  9. Click Create
  10. To execute, on the main menu, click Debug -> Start Without Debugging:

    Introduction to Forms

  11. Close the form and return to your programming environment

Introduction to Device Contexts

To draw something, you need a platform on which to draw and one or a few tools to draw with. The most common platform on which to draw is probably a piece of paper. Besides such a platform, you may need a pen or a brush that would show the evolution of the drawing work on the platform. Since a pen can have or use only one color, depending on your goal, one pen may not be sufficient, in which case you would end up with quite a few of them.

A device context is a group that includes the platform on which you draw and the tools you need to draw with. A device context also includes the dimensioning of the platform, the orientation and other variations of your drawing, the colors, and various other accessories that you can use to express your imagination.

When using a computer, you certainly cannot position tools on the table or desktop to use as needed. To help with drawing on a visual application, Microsoft created the Graphical Device Interface, abbreviated as GDI. It is a set of classes, functions, variables, and constants that group all or most of everything you need to draw on an application. GDI is provided as a library called Gdi.dll.

The GDI+ Library

GDI+ is the system used to perform drawing and other related graphics operations for the Microsoft Windows family of operating systems. Its predecessor was the Graphical Device Interface (GDI). GDI+ is installed in Microsoft operating systems. It functions in three fundamental concepts:

Getting to GDI+ 

The Graphics Platform

To draw in GDI, you have to obtain a handle to the device context. This is done by declaring a variable or a pointer to the HDC handle then calling a function such as BeginPaint() to initialize the device context. You also have to create the tools needed to draw. For example, you have to create a pen and/or a brush. Once the tools are ready, you have to select them into the device context to make them available. After drawing, it is suggested that you release the device context.

To draw in GDI+, you use an object referred to as graphic.

GDI+ Related Namespaces

To support GDI+ graphics and their features, the .NET Framework provides the System.Drawing namespace that is is created in the System.Drawing.dll library. This namespace also contains classes to draw or define a font in an application. To enhance the aspects of a drawing, the .NET Framework provides additional classes in the System.Drawing.Drawing2D namespace. This namespace also is defined in the System.Drawing.dll assembly. To support additional manipulation techniques that can be applied to a picture, the .NET Framework provides some other classes in the System.Drawing.Imaging namespace, which is also part of the System.Drawing.dll library.

The Graphics Object


The main object on which you will perform the drawings is called a graphic. In most cases, this object is not readily available when you need it: you must request it from the object on which you want to draw or you must create it. Both operations are highly easy.

A Graphics Class

To support computer graphics, the .NET Framework provides a class named Graphics:

public sealed class Graphics : MarshalByRefObject, IDisposable, System.Drawing.IDeviceContext

The Graphics class is defined in the System.Drawing namespace.

A Graphic for a Control

The Graphics class is defined in the System.Drawing namespace. Before drawing, you should obtain a graphic object. Fortunately, every Windows control, that is, every object based on the Control class, automatically inherits a method called CreateGraphics, which gives you access to the graphic part of a control. The syntax of the Control.CreateGraphics() method is:

public Graphics CreateGraphics();

As you can see, the CreateGraphics() method returns a Graphics object of the variable you call it from. Here is an example of getting the Graphics object of a form:

private void btnGraphics_Click(object sender, EventArgs e)
    Graphics graph = CreateGraphics();

A Handle for a Graphics Object

To serve a transition between Win32 and the .NET Framework, the Graphics class is equipped with a static method named FromHwnd. Its syntax is:

public static Graphics FromHwnd(IntPtr hwnd);

This method is static. The argument passed to it must be a handle to the object whose Graphics object you want to access. Every Windows control has a property named Handle. Here is an example of using it to get the Graphics part of a form:

private void btnGraphics_Click(object sender, EventArgs e)
    Graphics graph = Graphics.FromHwnd(this.Handle);

The Paint Event

In the .NET Framework programming, every visual Windows control is equipped with an event named Paint:

public event System.Windows.Forms.PaintEventHandler? Paint;

As you can see, this event is based on a delegate named PaintEventHandler:

public delegate void PaintEventHandler(object? sender, PaintEventArgs e);

As you can see, the PaintEventHandler delegate applies a class named PaintEventArgs:

public class PaintEventArgs : EventArgs, IDisposable, System.Drawing.IDeviceContext

To support graphics operations, the PaintEventArgs class is equippent with a read-only property named Graphics:

public System.Drawing.Graphics Graphics { get; }

Through the Control.Paint event, you get a Graphics object. You can get it from its e argument. Here is an example of getting a Graphics object:

private void Form1_Paint(object sender, PaintEventArgs e)
    e.Graphics . . . 

Practical LearningPractical Learning: Introducing the Paint Event

  1. Click the middle of the form
  2. In the Properties window, click the Events button Events
  3. Still in the Properties window, double-click Paint:
    namespace Exercise1
        public partial class Exercise : Form
            public Exercise()
            private void Exercise_Paint(object sender, PaintEventArgs e)

    Notice that the event is of type PaintEventArgs

  4. To execute, on the main menu, click Debug -> Start Without Debugging
  5. Close the form and return to your programming environment

The Process of Drawing

Getting a Device Context

As mentioned above, before drawing, make sure you have a Graphics object, which depends on your approach to drawing. To actually perform the drawing, the Graphics class provides various methods adapted for different shapes. Each method used to draw something has a name that starts with Draw... Also, each method that is used to draw a known shape requires a pen. Therefore, when drawing, your first decision will be based on the shape or type of figure you want to draw.

Two other pieces of information are particularly important with regards to any figure or shape you will need to draw: its location and dimensions.

The Origin of an Object

To keep track of the various drawings, the object on which you draw uses a coordinate system that has its origin (0, 0) on its top-left corner. If you are drawing on a form, this origin is positioned just under the title bar to the left:

The origin of the coordinate system and its axes

How you specify the values of the starting point of a shape or figure depends on the shape.

A Graphic as an Object

A Graphic Variable

In the body of a type (class, record, structure) or in a function or method, you can declare a variable of type Graphics variable as we have already seen. Here is an example of a Graphics field in a type:

public readonly struct Design
    Graphics gph;

After declaring the variable, make sure you properly initialize it before using it. We have seen various examples.

Disposing of a Graphic

As seen already, the Graphics class starts as follows:

public sealed class Graphics : MarshalByRefObject,

Notice that the Graphics class impliments the IDisposable interface. This means that, since a graphic consumes some resources, after using it, you should free the resources the object was using. This depends on how you got the graphic and how you used it. If you use the graphic object from a Paint event, you don't have to worry about its resources. Normally, if you declare a Graphics variable and initialize by indicating some means you got the object, then you must free its resources after use.

A Graphic Argument

When creating a function or method, if you find it necessary, you can create a graphic parameter. Here is an example:

public readonly struct Design
    public void Draw(Graphics graph)


In the body of the function or method, you can ignore or use the parameter. Of course, when calling the function or method, you must pass an argument for the parameter.

A Graphic Property

In a type (class, record, structure), you can create a property whose type is Graphics. You can create a complete property or an automatic one. Here is an example:

public readonly struct Design
    public Graphics Grapher { get; set; }

Practical LearningPractical Learning: Ending the Lesson

Home Copyright © 2010-2024, FunctionX Sunday 19 May 2024, 12:25 Next