[size="5"]Introduction
If you've been with me for the last two articles, you've probably been asking yourself when I'm going to show you something useful. Well, the wait is over! Today I'll be showing you the basics of Windows GDI (Graphical Device Interface), and a few other things along the way, like responding to user input and dealing with some more of the messages that Windows generates. As far as actually displaying graphics, I'm going to go over three basic topics: showing text, plotting pixels, and displaying bitmaps. Before getting into too much of that though, I'm going to cover several more Windows messages in detail so you will be sure to know what's going on when the user starts messing with things. They always do.
As always, you need only a basic knowledge of the C language, and the information that was covered in previous articles of this series. Since this article will enable you to make some working graphical demos, there is a sample program available along with the article. The code used for this program was written and compiled in Visual C++, but it is simple enough that you shouldn't have to change it to get it working with other compilers. All right, enough with the disclaimers, and on to the fun stuff!
[size="5"]Device Contexts
In the first article in this series, we defined and registered a window class. One of the lines in that definition, giving the window's capabilities, was this:
sampleClass.style = CS_DBLCLKS | CS_OWNDC |
CS_HREDRAW | CS_VREDRAW; // standard settings
A device context is a structure that represents a group of graphic objects and their attributes, as well as some output device and its attributes and settings. Using device contexts allows you to manipulate graphics in a very straightforward manner, without having to worry about a lot of low-level details. Windows GDI is a graphics-rendering system which takes Windows graphics calls and passes the information to the appropriate device driver. To make use of GDI graphics, you must use device contexts. Thankfully, it's very easy to do. You can get a device context for a window using a simple function call:
HDC GetDC( HWND hWnd // handle to a window );
Now is a good place to mention that device contexts are a little more general than dealing with graphics calls only. The type of DC we'll be talking about is called a display device context, because it deals with displaying graphics. In addition, there are printer device contexts, which use a printer as the output device; memory device contexts, which allow for manipulation of bitmap data; and information device contexts, for retrieving data for a specified device. Don't worry if this all sounds complicated. It's Windows -- its primary function is to confuse people. Once we get into some code, I think you'll find that it's actually not that difficult.
When you're finished with a device context, you have to release it. This frees up any memory that was being used by the object -- you'll come across the concept of releasing objects a lot more in the future. Once again, this is done by using a simple function call:
int ReleaseDC(
HWND hWnd, // handle to window
HDC hDC // handle to device context );
[font="Courier New"][color="#000080"]HWND hWnd[/color][/font]: This is the handle to the window which is referred to by the DC you're trying to release. If you have a DC for the whole desktop, pass [font="Courier New"][color="#000080"]NULL[/color][/font].
[font="Courier New"][color="#000080"]HDC hDC[/color][/font]: The handle to the device context you want to release.
Before we get into doing some graphics displays with device contexts and GDI, I want to talk about some of the important messages you'll encounter when creating a windowed application. The four messages I want to cover briefly are [font="Courier New"][color="#000080"]WM_MOVE[/color][/font], [font="Courier New"][color="#000080"]WM_SIZE[/color][/font], [font="Courier New"][color="#000080"]WM_ACTIVATE[/color][/font], and [font="Courier New"][color="#000080"]WM_PAINT[/color][/font].
[size="5"]Tracking the Status of Your Window
The first two are relatively simple. [font="Courier New"][color="#000080"]WM_MOVE[/color][/font] is called whenever the window is moved by the user. The new window coordinates are stored in [font="Courier New"][color="#000080"]lparam[/color][/font]. (Remember, messages are further specified by the contents of [font="Courier New"][color="#000080"]lparam[/color][/font] and [font="Courier New"][color="#000080"]wparam[/color][/font], which are parameters received by your message-handling function.) The low word of [font="Courier New"][color="#000080"]lparam[/color][/font] is the x-coordinate of the upper-left corner of the window's client area. The high word of [font="Courier New"][color="#000080"]lparam[/color][/font] is the y-coordinate.
The [font="Courier New"][color="#000080"]WM_SIZE[/color][/font] message is sent when the window is resized. Like the [font="Courier New"][color="#000080"]WM_MOVE[/color][/font] message, its parameterization is held in [font="Courier New"][color="#000080"]lparam[/color][/font]. The low word is the client area's width, and the high word is its height. But unlike [font="Courier New"][color="#000080"]WM_MOVE[/color][/font], the [font="Courier New"][color="#000080"]wparam[/color][/font] parameter also holds some significant. It can take any of the following values:
SIZE_MAXHIDESome other window has been maximized.SIZE_MAXIMIZEDWindow has been maximized.SIZE_MAXSHOWSome other window has been restored.SIZE_MINIMIZEDWindow has been minimized.SIZE_RESTOREDWindow has been resized, but neither maximized nor minimized.When I'm writing windowed applications, I usually like to keep a few global variables that give the window's current position and size. If these variables were called [font="Courier New"][color="#000080"]xPos[/color][/font], [font="Courier New"][color="#000080"]yPos[/color][/font], [font="Courier New"][color="#000080"]xSize[/color][/font], and [font="Courier New"][color="#000080"]ySize[/color][/font], you'd handle the [font="Courier New"][color="#000080"]WM_SIZE[/color][/font] and [font="Courier New"][color="#000080"]WM_MOVE[/color][/font] messages something like this:
if (msg == WM_SIZE)
{
xSize = LOWORD(lparam);
ySize = HIWORD(lparam);
}
if (msg == WM_MOVE)
{
xPos = LOWORD(lparam);
yPos = HIWORD(lparam);
}
The [font="Courier New"][color="#000080"]WM_ACTIVATE[/color][/font] message is sent to both the window being activated, and the window being deactivated. You can determine which is the case by looking at the low word of [font="Courier New"][color="#000080"]wparam[/color][/font]. It will be set to one of three possible values:
WA_CLICKACTIVEWindow was activated by a mouse click.WA_ACTIVEWindow was activated by some other means (keyboard, function call, etc.)WA_INACTIVEWindow was deactivated.For dealing with this message, I'll keep another global variable called bFocus, and change its value when a [font="Courier New"][color="#000080"]WM_ACTIVATE[/color][/font] message is received. The code would look something like this:
if (msg == WM_ACTIVATE)
{
if (LOWORD(wparam) == WA_INACTIVE)
focus = FALSE;
else
focus = TRUE;
// tell Windows we handled it
return(0);
}
[size="5"]The WM_PAINT Message
A window receives this important message when part of its client area has become invalidated. Suppose your program doesn't have the focus, and the active window is on top of your window. If the user moves that active window, it's going to reveal a part of your window. Since that part of the window needs to be refreshed, it is said to be invalidated. To handle this, there are a couple of things you can do. The first involves a pair of functions designed exclusively for use with the [font="Courier New"][color="#000080"]WM_PAINT[/color][/font] message. The first is [font="Courier New"][color="#000080"]BeginPaint()[/color][/font]. Here's the prototype:
HDC BeginPaint(
HWND hwnd, // handle to window
LPPAINTSTRUCT lpPaint // pointer to structure for paint information );
[font="Courier New"][color="#000080"]HWND hwnd[/color][/font]: This is a handle to the window which needs repainting. You should be used to seeing this parameter by now, right?
[font="Courier New"][color="#000080"]LPPAINTSTRUCT lpPaint[/color][/font]: Here's the important one. This is a pointer to a [font="Courier New"][color="#000080"]PAINTSTRUCT[/color][/font] structure, which contains all sorts of information about the area to be painted.
And before we go on, I should show you exactly what a [font="Courier New"][color="#000080"]PAINTSTRUCT[/color][/font] looks like...
typedef struct tagPAINTSTRUCT { // ps
HDC hdc;
BOOL fErase;
RECT rcPaint;
BOOL fRestore;
BOOL fIncUpdate;
BYTE rgbReserved[32];
} PAINTSTRUCT;
[font="Courier New"][color="#000080"]HDC hdc[/color][/font]: Aha! I knew there was some reason we went over device contexts, even if it took awile to get here. This is a DC that represents the invalidated area -- the area that needs to be painted.
[font="Courier New"][color="#000080"]BOOL fErase[/color][/font]: This specifies whether or not the application should erase the background. If set to [font="Courier New"][color="#000080"]FALSE[/color][/font], the system has already deleted the background. Remember in our window class when we defined a black brush as the background? This will cause the system to automatically erase the invalidated area with that black brush.
[font="Courier New"][color="#000080"]RECT rcPaint[/color][/font]: This is the most important member, as it tells you the rectangle that needs to be repainted in order to cover the whole invalidated area. I'll show you the [font="Courier New"][color="#000080"]RECT[/color][/font] structure in just a bit.
[font="Courier New"][color="#000080"]BOOL fRestore, BOOL fIncUpdate, BYTE rgbReserved[32][/color][/font]: Good news! These are reserved and are used by Windows, so you and I don't have to worry about them.
Now that I've showed this to you, I can tell you just what [font="Courier New"][color="#000080"]BeginPaint()[/color][/font] is accomplishing. It actually does three things. First, it validates the window again, so that another [font="Courier New"][color="#000080"]WM_PAINT[/color][/font] message will not be generated unless the window becomes invalidated again. Second, if your window class has a background brush defined, like ours does, it paints the affected area with that brush. Third, it returns a handle to a device context which represents the area needing to be painted. That area, as we saw, is defined by the important [font="Courier New"][color="#000080"]RECT[/color][/font] structure:
typedef struct _RECT {
LONG left;
LONG top;
LONG right;
LONG bottom;
} RECT;
RECT myRect = {0, 0, 5, 5};
Now, remember what I said about using device contexts? Once you're done using one, you have to release it. In this case, you use the [font="Courier New"][color="#000080"]EndPaint()[/color][/font] function. Each call to [font="Courier New"][color="#000080"]BeginPaint()[/color][/font], which should only be made in response to a [font="Courier New"][color="#000080"]WM_PAINT[/color][/font] message, must have a matching [font="Courier New"][color="#000080"]EndPaint()[/color][/font] function to release the DC. Here's the function:
BOOL EndPaint(
HWND hWnd, // handle to window
CONST PAINTSTRUCT *lpPaint // pointer to structure for paint data );
[font="Courier New"][color="#000080"]HWND hWnd[/color][/font]: Just the handle to the window. Again.
[font="Courier New"][color="#000080"]CONST PAINTSTRUCT *lpPaint[/color][/font]: A pointer to the [font="Courier New"][color="#000080"]PAINTSTRUCT[/color][/font] containing the information about the area in question. Don't let the [font="Courier New"][color="#000080"]CONST[/color][/font] confuse you. It's just there to denote and ensure that the function does not alter the contents of the structure.
For the record, the other way you can validate a window is with a call to [font="Courier New"][color="#000080"]ValidateRect()[/color][/font]. If you want to do everything manually instead of letting [font="Courier New"][color="#000080"]BeginPaint()[/color][/font] handle it, that's fine. There may be some cases where this is necessary. So here's the prototype:
BOOL ValidateRect(
HWND hWnd, // handle of window
CONST RECT *lpRect // address of validation rectangle coordinates );
[font="Courier New"][color="#000080"]HWND hWnd[/color][/font]: Are you getting tired of seeing this yet?
[font="Courier New"][color="#000080"]CONST RECT *lpRect[/color][/font]: This is a pointer to the [font="Courier New"][color="#000080"]RECT[/color][/font] to validate. Again, you don't need to declare it as a constant; the [font="Courier New"][color="#000080"]CONST[/color][/font] is just to make sure the function doesn't go changing things on you. If you pass [font="Courier New"][color="#000080"]NULL[/color][/font], the entire client area is validated.
Now, to wrap up our discussion of this message, I'll show you the framework for handling a [font="Courier New"][color="#000080"]WM_PAINT[/color][/font] message. This would be somewhere in your message handler, as usual. I'm assuming here that we have a global variable called [font="Courier New"][color="#000080"]hMainWindow[/color][/font] that is the handle to our window.
if (msg == WM_PAINT) {
PAINTSTRUCT ps; // declare a PAINTSTRUCT for use with this message
HDC hdc; // display device context for graphics calls
hdc = BeginPaint(hMainWindow, &ps); // validate the window
// your painting goes here!
EndPaint(hMainWindow, &ps); // release the DC
// tell Windows we took care of it
return(0);
}
[size="5"]Closing Your Application
There are three messages that seem to be practically identical, and all deal with closing things out. They are [font="Courier New"][color="#000080"]WM_DESTROY[/color][/font], [font="Courier New"][color="#000080"]WM_CLOSE[/color][/font], and [font="Courier New"][color="#000080"]WM_QUIT[/color][/font]. They're similar, but you need to know the difference! [font="Courier New"][color="#000080"]WM_CLOSE[/color][/font] is sent when a window or application should be closing. When you receive a [font="Courier New"][color="#000080"]WM_CLOSE[/color][/font] message, it's a good place to ask the user if they're sure they want to quit, if you want to do it. You know those little message boxes that are always popping up on your screen when errors or notifications occur? Well, they're easy to create. In addition to serving many functions in the final program, they're also handy for reporting debug information. The call to create your very own message box is pretty simple:
int MessageBox(
HWND hWnd, // handle of owner window
LPCTSTR lpText, // address of text in message box
LPCTSTR lpCaption, // address of title of message box
UINT uType // style of message box );
[font="Courier New"][color="#000080"]HWND hWnd[/color][/font]: Sooner or later we'll get to a function that doesn't have this, I promise!
[font="Courier New"][color="#000080"]LPCTSTR lpText[/color][/font]: This is the text that will appear in the message box. As always, you can use escape sequences like [font="Courier New"][color="#000080"]\n[/color][/font] to format the output a little if you want.
[font="Courier New"][color="#000080"]LPCTSTR lpCaption[/color][/font]: This is the text appearing in the message box's caption bar.
[font="Courier New"][color="#000080"]UINT uType[/color][/font]: You can combine several different flags in order to create this parameter, which defines what kind of message box it will be. There are a lot of [font="Courier New"][color="#000080"]MB_[/color][/font] constants you can use, and you can combine any number of them with the | operator. Here's a list of the useful ones:
Button Definition FlagsMB_ABORTRETRYIGNORECreates a box with "Abort," "Retry," and "Ignore" buttons.MB_OKCreates a box with an "OK" button.MB_OKCANCELCreates a box with "OK" and "Cancel" buttons.MB_RETRYCANCELCreates a box with "Retry" and "Cancel" buttons.MB_YESNOCreates a box with "Yes" and "No" buttons.MB_YESNOCANCELCreates a box with "Yes," "No," and "Cancel" buttons.Icon Definition FlagsMB_ICONEXCLAMATIONAdds an exclamation point icon to the box.MB_ICONINFORMATIONAdds an information icon to the box.MB_ICONQUESTIIONAdds a question mark icon to the box.MB_ICONSTOPAdds a stop sign icon to the box.Default Button FlagsMB_DEFBUTTON1Defines the first button as the default.MB_DEFBUTTON2Defines the second button as the default.MB_DEFBUTTON3Defines the third button as the default.MB_DEFBUTTON4Defines the fourth button as the default.Other FlagsMB_HELPAdds a help button to the box. A WM_HELP message is generated if the user chooses it or presses F1.MB_RIGHTMessage box text is right-justified.MB_TOPMOSTSets the message box to always be the topmost window.I don't know about you, but I'm starting to think that Microsoft has a programmer who does nothing but write [font="Courier New"][color="#000080"]#define[/color][/font] statements all day! Now, the return value is 0 if the box could not be created. Otherwise, the result is one of the following:
IDABORT"Abort" button was selected.IDCANCEL"Cancel" button was selected.IDIGNORE"Ignore" button was selected.IDNO"No" button was selected.IDOK"OK" button was selected.IDRETRY"Retry" button was selected.IDYES"Yes" button was selected.Those lists were so long I almost forgot what we were originally talking about. Anyway, when you receive a [font="Courier New"][color="#000080"]WM_CLOSE[/color][/font] message, you can do two things. First, you can allow the default handler to return a value. If you do this, the application or window will close as planned. However, if you return 0, the message will have no effect. This is the basis of the following bit of code:
if (msg == WM_CLOSE) {
if (MessageBox(hMainWindow,
"Are you sure want to quit?",
"Notice",
MB_YESNO | MB_ICONEXCLAMATION) == IDNO)
return(0);
// otherwise, let the default handler take care of it
}
VOID PostQuitMessage(int nExitCode);
int WinMain(HINSTANCE hinstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow)
{
// initialization stuff goes here
// main loop - infinite!
while (TRUE)
{
// check the message queue
if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
if (msg.message == WM_QUIT) // exit main loop on WM_QUIT
break;
TranslateMessage(&msg);
DispatchMessage(&msg);
}
// main program logic goes here
}
// perform any shutdown functions here - releasing objects and such
return(msg.wparam); // return exit code to Windows
}
[size="5"]Plotting Pixels
At last! Plotting pixels with GDI is a cinch as long as you've got a display device context to work with. Remember, calling [font="Courier New"][color="#000080"]GetDC()[/color][/font] does this for you. To plot a pixel, not surprisingly, you call [font="Courier New"][color="#000080"]SetPixel()[/color][/font]:
COLORREF SetPixel(
HDC hdc, // handle to device context
int X, // x-coordinate of pixel
int Y, // y-coordinate of pixel
COLORREF crColor // pixel color );
[font="Courier New"][color="#000080"]HDC hdc[/color][/font]: This is a device context for your window that you should obtain with a call to [font="Courier New"][color="#000080"]GetDC()[/color][/font]. You only need to call [font="Courier New"][color="#000080"]GetDC()[/color][/font] once, and then you can use it for any number of these functions. Don't get a new DC every time you want to plot a pixel!
[font="Courier New"][color="#000080"]int X, Y[/color][/font]: The x- and y-coordinates of the pixel. These are in client coordinates, meaning that (0, 0) represents the upper-left corner of your window's client area, not the upper-left corner of the screen.
[font="Courier New"][color="#000080"]COLORREF crColor[/color][/font]: This is the color you want to set the pixel to. To do this, it's easiest to use the [font="Courier New"][color="#000080"]RGB()[/color][/font] macro, which takes values for red, green, and blue -- in that order -- between 0 and 255. [font="Courier New"][color="#000080"]SetPixel()[/color][/font] will choose the closest available color to the one you have specified.
If the function succeeds, the return value is the color that the pixel was set to. This may not always be exactly the [font="Courier New"][color="#000080"]COLORREF[/color][/font] you pass if you're working in less than 24-bit color; Windows will choose the closest match. If the function fails, it returns -1. As an example, if you want to set the upper-left corner of your client area to white, you'd use the following call:
SetPixel(hdc, 0, 0, RGB(255, 255, 255));
BOOL SetPixelV(
HDC hdc, // handle to device context
int X, // x-coordinate of pixel
int Y, // y-coordinate of pixel
COLORREF crColor // new pixel color );
The only other thing you need to know about plotting pixels is how to read the value of a pixel that's already been plotted. It's no problem; a quick call to [font="Courier New"][color="#000080"]GetPixel()[/color][/font] does the job for you:
COLORREF GetPixel(
HDC hdc, // handle to device context
int XPos, // x-coordinate of pixel
int nYPos // y-coordinate of pixel );
[size="5"]GDI Text Functions
There are two functions for actually plotting text that you need to be concerned with. The simpler of the two is [font="Courier New"][color="#000080"]TextOut()[/color][/font], as shown here:
BOOL TextOut(
HDC hdc, // handle to device context
int nXStart, // x-coordinate of starting position
int nYStart, // y-coordinate of starting position
LPCTSTR lpString, // pointer to string
int cbString // number of characters in string );
[font="Courier New"][color="#000080"]HDC hdc[/color][/font]: The device context to use.
[font="Courier New"][color="#000080"]int nXStart, nYStart[/color][/font]: These are the coordinates of the starting point for the text, called the reference point. By default, this is the upper-left corner of the rectangular area occupied by the string. You can change this setting, as we'll see in just a bit.
[font="Courier New"][color="#000080"]LPCTSTR lpString[/color][/font]: The text to print out. Since the number of characters is given in the final parameter, this string does not need to be null-terminated.
[font="Courier New"][color="#000080"]int cbString[/color][/font]: This is the length of the string, in characters.
[font="Courier New"][color="#000080"]TextOut()[/color][/font] uses the current settings for text color, background color, and background type. Before looking at the other, more complicated text-rendering function, let's take a look at the functions you can use to control the colors being used.
COLORREF SetTextColor(
HDC hdc, // handle to device context
COLORREF crColor // text color );
COLORREF SetBkColor(
HDC hdc, // handle of device context
COLORREF crColor // background color value );
int SetBkMode(
HDC hdc, // handle of device context
int iBkMode // flag specifying background mode );
One more thing about [font="Courier New"][color="#000080"]TextOut()[/color][/font]. I said you could change the way the reference point is interpreted, and the way to do it is by using [font="Courier New"][color="#000080"]SetTextAlign()[/color][/font], whose prototype is shown below.
UINT SetTextAlign(
HDC hdc, // handle to device context
UINT fMode // text-alignment flag );
[font="Courier New"][color="#000080"]HDC hdc[/color][/font]: The device context again. No surprises here.
[font="Courier New"][color="#000080"]UINT fMode[/color][/font]: A flag or set of flags (logically combined with |) that determine the meaning of the reference point in a call to [font="Courier New"][color="#000080"]TextOut()[/color][/font]. Only one flag can be selected from those affecting horizontal and vertical alignment, and only one of the two flags affecting use of the current position can be used. The flags are:
TA_BASELINEThe reference point will be on the baseline of the text.TA_BOTTOMThe reference point will be on the bottom edge of the bounding rectangle.TA_TOPThe reference point will be on the top edge of the bounding rectangle.TA_CENTERThe reference point will be aligned horizontally with the center of the bounding rectangle.TA_LEFTThe reference point will be on the left edge of the bounding rectangle.TA_RIGHTThe reference point will be on the right edge of the bounding rectangle.TA_NOUPDATECPThe current position is not updated by a call to a text output function. The reference point is passed with each call.TA_UPDATECPThe current position is updated by each call to a text output function, and is used as the reference point.The default setting is [font="Courier New"][color="#000080"]TA_LEFT | TA_TOP | TA_NOUPDATECP[/color][/font]. If you set [font="Courier New"][color="#000080"]TA_UPDATECP[/color][/font], subsequent calls to [font="Courier New"][color="#000080"]TextOut()[/color][/font] will ignore the [font="Courier New"][color="#000080"]nXStart[/color][/font] and [font="Courier New"][color="#000080"]nYStart[/color][/font] parameters, and render the text where the last call left off. Now that that's out of the way, let's look at the bells-and-whistles version of [font="Courier New"][color="#000080"]TextOut()[/color][/font], called [font="Courier New"][color="#000080"]DrawText()[/color][/font]:
int DrawText(
HDC hDC, // handle to device context
LPCTSTR lpString, // pointer to string to draw
int nCount, // string length, in characters
LPRECT lpRect, // pointer to struct with formatting dimensions
UINT uFormat // text-drawing flags );
[font="Courier New"][color="#000080"]HDC hDC[/color][/font]: Nothing new here; it's just our good buddy the DC.
[font="Courier New"][color="#000080"]LPCTSTR lpString[/color][/font]: This is the string to print.
[font="Courier New"][color="#000080"]int nCount[/color][/font]: This is the length of the string in characters.
[font="Courier New"][color="#000080"]LPRECT lpRect[/color][/font]: Here's where things start to get a bit different. [font="Courier New"][color="#000080"]DrawText()[/color][/font] does several different methods of formatting, including word wrapping, so you must specify a [font="Courier New"][color="#000080"]RECT[/color][/font] within which to format the text, rather than simply passing coordinates.
[font="Courier New"][color="#000080"]UINT uFormat[/color][/font]: For this, you can use one or more (logically combined with |) of a long list of flags that represent different methods of formatting. I'll show you a few of them.
DT_BOTTOMJustifies text to the bottom of the RECT. This must be combined with DT_SINGLELINE.DT_CALCRECTCalculates the RECT needed to hold the text. If the text is on multiple lines, DrawText() uses your RECT's width and alters the height. If the text is on a single line, DrawText() alters your RECT's width. In both cases, DrawText() adjusts the RECT but does not actually draw the text.DT_CENTERCenters text within the RECT you specify.DT_EXPANDTABSIf the string contains any tabs (\t), this attribute causes DrawText() to expand them. The default is eight spaces per tab.DT_LEFTLeft-justifies the text.DT_NOCLIPDraws without clipping. This speeds up DrawText() a bit.DT_RIGHTRight-justifies the text.DT_SINGLELINEDisplays text on a single line only. Carriage returns and line feeds do not overrule this attribute.DT_TABSTOPAlters the number of spaces per tab. The number of spaces per tab must be specified in bits 15-8 (the high byte of the low word) of uFormat. Again, the default setting is eight.DT_TOPJustifies text to the top of the RECT. This must be combined with DT_SINGLELINE.DT_VCENTERCenters the text vertically within the RECT. This must be combined with DT_SINGLELINE.There are more of these flags, but you get the idea. All in all, this constitutes a pretty powerful text rendering system, but remember, all those cool features are going to slow the function down. You can usually get by just fine by using [font="Courier New"][color="#000080"]TextOut()[/color][/font]. That takes care of the text rendering system, so let's do something a little more exciting.
[size="5"]Displaying Bitmaps With GDI
Remember when I told you that bitmaps are easy to work with, because they're native to Windows? Well now we're going to find out just how easy it is. There are four basic steps to displaying a bitmap with GDI:
- Get a device context to your window.
- Obtain a handle to the bitmap.
- Create a device context for the bitmap.
- Copy the image from one device context to the other.
HANDLE LoadImage(
HINSTANCE hinst, // handle of the instance containing the image
LPCTSTR lpszName, // name or identifier of image
UINT uType, // type of image
int cxDesired, // desired width
int cyDesired, // desired height
UINT fuLoad // load flags );
[font="Courier New"][color="#000080"]HINSTANCE hinst[/color][/font]: This should be the instance of your application if you're loading a resource, or [font="Courier New"][color="#000080"]NULL[/color][/font] if you want to load from an external file.
[font="Courier New"][color="#000080"]LPCTSTR lpszName[/color][/font]: This is either the resource identifier -- remember to use [font="Courier New"][color="#000080"]MAKEINTRESOURCE()[/color][/font] if you're using numerical constants -- or the full filename of the image you want to load.
[font="Courier New"][color="#000080"]UINT uType[/color][/font]: Depending on what you want to load, this should be set to either [font="Courier New"][color="#000080"]IMAGE_BITMAP[/color][/font], [font="Courier New"][color="#000080"]IMAGE_CURSOR[/color][/font], or [font="Courier New"][color="#000080"]IMAGE_ICON[/color][/font].
[font="Courier New"][color="#000080"]int cxDesired, cyDesired[/color][/font]: These are the desired dimensions for the image to be loaded. If you set them to zero, the image's actual dimensions will be used.
[font="Courier New"][color="#000080"]UINT fuLoad[/color][/font]: Like everything else we've done today, this is one or more of a series of flags which can be logically combined with the | operator. Here are the useful flags:
LR_CREATEDIBSECTIONIf uType is IMAGE_BITMAP, this causes the function to return a DIB section rather than a compatible bitmap. (DIB stands for device-independent bitmap.) This basically means to use all of the bitmap's own properties rather than making it conform to the properties of the display device.LR_DEFAULTSIZEFor icons and cursors, if cxDesired and cyDesired are set to 0, this flag causes the system metric values for icons and cursors to be used, rather than the actual dimensions of the image.LR_LOADFROMFILEYou must specify this flag if you want to load from a file rather than a resource. For loading bitmaps you should use [font="Courier New"][color="#000080"]LR_CREATEDIBSECTION[/color][/font], and [font="Courier New"][color="#000080"]LR_LOADFROMFILE[/color][/font] if it is appropriate. Now that you have obtained a handle to your image, you must create a device context and load the bitmap into it. The first step is taken by calling [font="Courier New"][color="#000080"]CreateCompatibleDC()[/color][/font], as follows:
HDC CreateCompatibleDC(HDC hdc);
HGDIOBJ SelectObject(
HDC hdc, // handle to device context
HGDIOBJ hgdiobj // handle to object );
[font="Courier New"][color="#000080"]HDC hdc[/color][/font]: This is a handle to the device context which we want to fill with an object. For loading bitmaps, this must be a memory device context.
[font="Courier New"][color="#000080"]HGDIOBJ hgdiobj[/color][/font]: And this is a handle to that object. This function is used with bitmaps, brushes, fonts, pens, and regions; but the only one that concerns us is bitmaps.
The return value is a handle to the object that is being replaced in the DC, or [font="Courier New"][color="#000080"]NULL[/color][/font] if an error occurs. The return values are different for regions, but like I said, we don't care about regions.
Now you've got a bitmap loaded into a DC, and you need only take the last step: copying the contents of the memory device context to our display device context. However, it's necessary to obtain some information about the bitmap, such as its dimensions, which must be used in the function call that will display the image. For that, we need the [font="Courier New"][color="#000080"]GetObject()[/color][/font] function, which is used for obtaining information about graphical objects such as bitmaps.
int GetObject(
HGDIOBJ hgdiobj, // handle to graphics object of interest
int cbBuffer, // size of buffer for object information
LPVOID lpvObject // pointer to buffer for object information );
[font="Courier New"][color="#000080"]HGDIOBJ hgdiobj[/color][/font]: The handle to the graphics object we want information on. In this case, pass the handle to the bitmap we loaded.
[font="Courier New"][color="#000080"]int cbBuffer[/color][/font]: This is the size of the structure receiving the information. In the case of loading bitmaps, the receiving structure is of type [font="Courier New"][color="#000080"]BITMAP[/color][/font], so set this to [font="Courier New"][color="#000080"]sizeof(BITMAP)[/color][/font].
[font="Courier New"][color="#000080"]LPVOID lpvObject[/color][/font]: Pass the address of the structure receiving the information.
You need to define a variable of type [font="Courier New"][color="#000080"]BITMAP[/color][/font], and with a quick call to the [font="Courier New"][color="#000080"]GetObject()[/color][/font] function, you'll have the information you need. Since the [font="Courier New"][color="#000080"]BITMAP[/color][/font] structure is new to us, I'll show you what it looks like:
typedef struct tagBITMAP { // bm
LONG bmType;
LONG bmWidth;
LONG bmHeight;
LONG bmWidthBytes;
WORD bmPlanes;
WORD bmBitsPixel;
LPVOID bmBits;
} BITMAP;
[font="Courier New"][color="#000080"]LONG bmType[/color][/font]: This is the bitmap type and must be set to zero. Useful, isn't it?
[font="Courier New"][color="#000080"]LONG bmWidth, bmHeight[/color][/font]: These are the two we're after -- the width and height of the bitmap, in pixels.
[font="Courier New"][color="#000080"]LONG bmWidthBytes[/color][/font]: Specifies the number of bytes in each line of the bitmap. Note that the number of bytes per pixel can be obtained by dividing this value by [font="Courier New"][color="#000080"]bmWidth[/color][/font].
[font="Courier New"][color="#000080"]LONG bmPlanes[/color][/font]: This is the number of color planes.
[font="Courier New"][color="#000080"]LONG bmBitsPixel[/color][/font]: This is the number of bits required to represent one pixel. It would appear that the note I left about figuring this out is useless.
[font="Courier New"][color="#000080"]LPVOID bmBits[/color][/font]: If you want to access the actual image data, this is a pointer to the bit values for the bitmap.
All right, almost done! Now we have the bitmap in a memory device context, and we know its dimensions. All we have to do is cop