Home > Articles > Programming

This chapter is from the book

This chapter is from the book

Painting Windows

The Win32 API includes a special message that is delivered to a window whenever it needs to be painted. This message is called WM_PAINT, and it serves as one of the main ways in which graphics are drawn to a window. A window might need to be repainted when the window is first created, when the window is uncovered from behind other windows, or for a variety of other reasons. The bottom line is that you must handle the WM_PAINT message in order to paint the inside (client area) of a window.

When I refer to painting or drawing to a window, I'm really referring to the client area of a window. This is the rectangular part of a window inside the window's border that doesn't include the window frame, caption, menu, system menu, or scrollbars. Figure 3.5 reveals how the coordinates of the client area begin in the upper-left corner of the window and increase down and to the right, as you learned earlier in the chapter. This coordinate system is very important because most GDI graphics operations are based on it.

Figure 3.5Figure 3.5 Most graphics in a Windows program are drawn to the client area of a window, which uses the Windows graphics coordinate system.

As you might recall, message handling takes place in the WndProc() function for a window. However, we were smart enough to make things simpler with the game engine you created in the previous chapter. More specifically, a WndProc() function is hidden in the game engine that handles the WM_PAINT message and calls the GamePaint() function. However, the call to the GamePaint() function is sandwiched between calls to the Win32 BeginPaint() and EndPaint() functions. This allows you to place graphics code in the GamePaint() function of your game without having to worry about obtaining a device context. The following is the WM_PAINT message handler in the WndProc() function, which shows how the GamePaint() function is called:

case WM_PAINT:
 HDC     hDC;
 PAINTSTRUCT ps;
 hDC = BeginPaint(hWindow, &ps);

 // Paint the game
 GamePaint(hDC);

 EndPaint(hWindow, &ps);
 return 0;

The device context obtained from BeginPaint() is passed into the GamePaint() function to delegate the specifics of drawing graphics to each individual game. The following is an example of a simple GamePaint() function:

void GamePaint(HDC hDC)
{
 *** GDI drawing operations go here ***
}

GDI painting operations are performed on a device context or DC, which is passed into the function via the hDC argument. The following is an example of drawing a line in the GamePaint() function:

void GamePaint(HDC hDC)
{
 MoveToEx(hDC, 0, 0, NULL);
 LineTo(hDC, 50, 50);
}

This code shows how to draw a line using GDI functions. You learn more about how these functions work in a moment, but first, let's take a look at how to draw text.

Painting Text

In Windows, text is treated no differently from graphics, which means that text is painted using GDI functions. The primary GDI function used to paint text is TextOut(), which looks like this:

BOOL TextOut(HDC hDC, int x, int y, LPCTSTR szString, int iLength);

The following are the meanings of the different arguments to the TextOut() function:

  • hDC—Device context handle

  • x—X coordinate of text position

  • y—Y coordinate of text position

  • szString—The string to be painted

  • iLength—Length of the string to be painted

The first argument to TextOut() is a handle to a device context, which is provided by the BeginPaint() function. All GDI functions require a handle to a device context, so you should get comfortable with seeing it in graphics code. The x and y arguments specify the position of the upper-left corner of the first string character relative to the client area (see Figure 3.6), whereas the last two arguments are a pointer to a string and the length of the string, in characters.

Figure 3.6Figure 3.6 Text is drawn at the upper-left corner of the first character with respect to the client area of a window.

The following is an example of how to use the TextOut() function to draw a simple string of text:

void GamePaint(HDC hDC)
{
 TextOut(hDC, 10, 10, TEXT("Michael Morrison"), 16);
}

Another text-related function that you might consider using is DrawText(), which allows you to draw text within a rectangle, as opposed to drawing it at a specified point. As an example, you can use DrawText() to center a line of text on the screen by specifying the entire client window as the rectangle in which to draw the text. The following is an example of using the DrawText() function in place of TextOut():

void GamePaint(HDC hDC)
{
 RECT rect;
 GetClientRect(hWindow, &rect);
 DrawText(hDC, TEXT("Michael Morrison"), -1, &rect,
  DT_SINGLELINE | DT_CENTER | DT_VCENTER);
}

In this example, the text is drawn centered both horizontally and vertically in the entire client area of the window. Notice that the length of the text string isn't necessary; this is because -1 is provided as the length, which means that the length should be automatically determined because the string is null-terminated. The flags in the last argument of DrawText() are used to determine how the text is drawn, which in this case, causes the text to be centered both horizontally and vertically.

Painting Primitive Graphics

Graphics primitives form a fundamental part of GDI and consist of lines, rectangles, circles, polygons, ovals, and arcs. You can create pretty impressive graphics by using these primitives in conjunction with each other. If you think graphics primitives sound somewhat limiting, keep in mind that some of the most enduring arcade games of all time were created solely through graphics primitives. Lunar Lander, Asteroids, Tempest, Gravitar, and Space Duel are a few of the classic vector arcade games whose graphics consisted solely of primitives.

The following are the major graphics primitives you can paint with GDI functions:

  • Lines

  • Rectangles

  • Ellipses

  • Polygons

The next few sections demonstrate how to draw each of these graphics primitives, along with how to use pens and brushes to add color to them.

Lines

Lines are the simplest of the graphics primitives and are therefore the easiest to draw. Lines are painted using the MoveToEx() and LineTo() functions, which set the current position and draw a line connecting the current position to a specified end point, respectively. The idea is that you use MoveToEx() to move the pen to a certain point and then use LineTo() to draw a line from that point to another point. You can continue to draw lines connecting points by calling LineTo() again. The following are what these functions look like:

BOOL MoveToEx(HDC hDC, int x, int y, LPPOINT pt);
BOOL LineTo(HDC hDC, int x, int y);

NOTE

An XY coordinate in Windows is referred to as a point and is often represented by the Win32 POINT structure. The POINT structure is used throughout Windows to represent coordinates for a variety of different operations. The POINT structure consists solely of two long integer fields, x and y.

Both functions accept a handle to a device context and an X and Y value for the point of the line. The MoveToEx() function also allows you to provide an argument to store the previous point. In other words, you can pass a pointer to a point as the last argument of MoveToEx() if you're interested in finding out the last point used for drawing. The following is an example of using MoveToEx() and LineTo() to draw a couple of lines:

void GamePaint(HDC hDC)
{
 MoveToEx(hDC, 10, 40, NULL);
 LineTo(hDC, 44, 10);
 LineTo(hDC, 78, 40);
}

In this code, the drawing position is first set by calling MoveToEx() and providing the XY position of a point. Notice that the final argument is passed as NULL, which indicates that you aren't interested in finding out the previous point. The LineTo() function is then called twice, which results in two connected lines being drawn.

Rectangles

Rectangles represent another type of graphics primitive that is very easy to draw. The Rectangle() function enables you to draw a rectangle by specifying the upper-left corner and the lower-right corner of the rectangle. The following is the prototype for the Rectangle() function, which helps to reveal its usage:

BOOL Rectangle(HDC hDC, int xLeft, int yTop, int xRight, int yBottom);

NOTE

To draw a perfect square using the Rectangle() function, just specify a rectangle that has an equal width and height.

The Rectangle() function is straightforward in that you pass it rectangular dimensions of the bounding rectangle for the rectangle to be painted. The following is an example of how to draw a couple of rectangles:

void GamePaint(HDC hDC)
{
 Rectangle(hDC, 16, 36, 72, 70);
 Rectangle(hDC, 34, 50, 54, 70);
}

There isn't really anything remarkable about this code; it simply draws two rectangles of differing sizes and positions. Don't forget that the last two arguments to the Rectangle() function are the X and Y positions of the lower-right corner of the rectangle, not the width and height of the rectangle.

Another handy rectangle function is FillRect(), which is used to simply fill a rectangular area with a particular color. The color used for the filling is determined by the brush passed into the function. The following is the prototype for the FillRect() function:

int FillRect(HDC hDC, CONST RECT *lprc, HBRUSH hbr);

Unlike the Rectangle() function, the FillRect() function accepts a pointer to a RECT structure instead of four separate rectangle values. You'll also notice that the FillRect() function accepts a brush handle as its third argument. The FillRect() function is put to good use later in the chapter when you build the Crop Circles example.

Ellipses

Although they are curved, ellipses are drawn in a manner very similar to rectangles. An ellipse is simply a closed curve, and therefore, it can be specified by a bounding rectangle. The circular explosions in the classic Missile Command game provide a very good example of a filled ellipse. Ellipses are painted using the Ellipse() function, which looks like this:

BOOL Ellipse(HDC hDC, int xLeft, int yTop, int xRight, int yBottom);

NOTE

To draw a perfect circle using the Ellipse() function, just specify a rectangle that has an equal width and height.

The Ellipse() function accepts the rectangular dimensions of the bounding rectangle for the ellipse to be painted. The following is an example of drawing an ellipse using the Ellipse() function:

void GamePaint(HDC hDC)
{
 Ellipse(hDC, 40, 55, 48, 65);
}

Not surprisingly, this code draws an ellipse based on four values that specify a bounding rectangle for the ellipse.

NOTE

Arcs, chords, and pies can also be drawn using Win32 GDI functions very similar to the Ellipse() function.

Polygons

The trickiest of graphics primitives is the polygon, which is a closed shape consisting of multiple line segments. The asteroid shapes in the popular Asteroids game offer a great example of polygons. Polygons are painted using the Polygon() function, which follows:

BOOL Polygon(HDC hDC, CONST POINT* pt, int iCount);

As you can see, the Polygon() function is a little more complex than the other graphics primitives functions in that it takes an array of points and the number of points as arguments. A polygon is painted by connecting each of the points in the array with lines. The following is an example of how to draw a polygon shape using the Polygon() function:

void GamePaint(HDC hDC)
{
 POINT points[3];
 points[0] = { 5, 10 };
 points[1] = { 25, 30 };
 points[2] = { 15, 20 };
 Polygon(hDC, points, 3);
}

The key to this code is the creation of the array of points, points, which contains three POINT structures. These three POINT structures are initialized with XY pairs, and the whole array is then passed into the Polygon() function, along with the total number of points in the array. That's all that is required to draw a polygon shape consisting of multiple line segments.

Working with Pens and Brushes

It's one thing to simply draw graphics primitives in their default mundane black and white style. It's quite another to control the line and fill colors of the primitives to get more interesting results. This is accomplished by using pens and brushes, which are standard GDI objects used in drawing graphics primitives. Whether you realize it or not, you're already using pens and brushes when you draw graphics primitives. It's just that the default pen is black, and the default brush is the same color as the window background.

Creating Pens

If you want to change the outline of a graphics primitive, you need to change the pen used to draw it. This typically involves creating a new pen, which is accomplished with the CreatePen() function:

HPEN CreatePen(int iPenStyle, int iWidth, COLORREF crColor);

The first argument is the style of the pen, which can be one of the following values: PS_SOLID, PS_DASH, PS_DOT, PS_DASHDOT, PS_DASHDOTDOT, or PS_NULL. All but the last value specify different kinds of lines drawn with the pen, such as solid, dashed, dotted, or a combination of dashed and dotted. The last value, PS_NULL, indicates that no outline is to be drawn; in other words, the pen doesn't draw. The second argument to CreatePen() is the width of the pen in logical units, which typically corresponds to pixels when drawing to the screen. The final argument is the color of the pen, which is specified as a COLORREF value. To help make things clear, the following is an example of how to create a solid blue pen that is one-pixel wide:

HPEN hBluePen = CreatePen(PS_SOLID, 1, RGB(0, 0, 255));

Keep in mind that simply creating a pen isn't enough to begin drawing with it. In a moment, you learn how to select a pen into a device context and begin drawing with it. However, let's first learn how to create brushes.

Creating Brushes

Although several different kinds of brushes are supported in the GDI, I'd like to focus on solid brushes, which allow you to fill in graphics shapes with a solid color. You create a solid brush using the Win32 CreateSolidBrush() function, which simply accepts a COLORREF structure. The following is an example of creating a purple brush:

HBRUSH hPurpleBrush = CreateSolidBrush(RGB(255, 0, 255));

Notice in this code that a value of 255 is used to set the red and blue components of the color, which is how you are achieving purple in the final mixed color; try out this color combination in Paint to see how it results in purple. Now that you have a handle to a brush, you're ready to select it into a device context and begin painting with it.

Selecting Pens and Brushes

In order to use a pen or brush you've created, you must select it into a device context using the Win32 SelectObject() function. This function is used to select graphics objects into a device context and applies to both pens and brushes. The following is an example of selecting a pen into a device context:

HPEN hPen = SelectObject(hDC, hBluePen);

In this example, the hBluePen you just created is selected into the device context. Also notice that the previously selected pen is returned from SelectObject() and stored in hPen. This is important because you will typically want to restore GDI settings to their original state when you're finished painting. In other words, you want to remember the original pen so that you can set it back when you're finished. The following is an example of restoring the original pen using SelectObject():

SelectObject(hDC, hPen);

Notice that it is no longer important to remember the return value of SelectObject() because you are restoring the original pen.

One more important task related to creating pens is that of deleting graphics objects that you create. This is accomplished with the DeleteObject() function, which applies to both pens and brushes. It is important to delete any graphics objects that you create after you've stopped using them and they are no longer selected into a device context. The following is an example of cleaning up the blue pen:

DeleteObject(hBluePen);

Selecting and deleting brushes is very similar to selecting and deleting pens. The following is a more complete example to illustrate:

HBRUSH hBrush = SelectObject(hDC, hPurpleBrush);
// *** Do some drawing here! ***
SelectObject(hDC, hBrush);
DeleteObject(hPurpleBrush);

In this example, the purple brush from the previous section is selected into the device context, some drawing is performed, and the old brush is restored. The purple brush is then deleted to clean up everything.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020