0% found this document useful (0 votes)
24 views19 pages

2c6bb591 1701243044672

The document discusses Windows Graphics Device Interface (GDI) capabilities. It describes how to display text, pixels, lines, and filled shapes using GDI functions. It also covers creating and selecting pens and brushes to determine drawing colors and styles. The document provides code examples for common GDI tasks like drawing text, lines, rectangles, and ellipses. It notes that GDI can be used in all Windows applications for graphics and formatted text display on screens and printers.

Uploaded by

kashyaputtam7
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views19 pages

2c6bb591 1701243044672

The document discusses Windows Graphics Device Interface (GDI) capabilities. It describes how to display text, pixels, lines, and filled shapes using GDI functions. It also covers creating and selecting pens and brushes to determine drawing colors and styles. The document provides code examples for common GDI tasks like drawing text, lines, rectangles, and ellipses. It notes that GDI can be used in all Windows applications for graphics and formatted text display on screens and printers.

Uploaded by

kashyaputtam7
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Unit 13: Windows GDI

Notes

Notes In GDI calls screen position 0,0 is the top left of the window. If you need to work out
the window width and height follow this link here: Window size

An example application showing these GDI functions can be downloaded here: WinGDIdemo.exe.
In addition the source code for this demo can also be downloaded: WinGDIDemoCode.zip

The different GDI capabilities:

 Displaying Text

 Displaying Pixels
 Drawing Lines

 Drawing Filled Shapes

 Pens & Brushes

 Window size

 Forcing a redraw

13.1.1 Displaying Text

To display some text you can use the TextOut function. In order to use this you need to obtain a
handle to the device, an HDC and release it after use.

To obtain the handle you call: BeginPaint, it takes your window handle and a pointer to a
PAINTSTRUCT that you have declared. This structure is just used by windows so you don't need
to do anything apart from pass it on to functions.

The definition of the TextOut function is:

BOOL TextOut(HDC hdc, int x, int y, LPCSTR lpString, int cbString);

It takes the handle you were returned from BeginPaint, the x, y position on screen, a pointer to
some text and the number of characters you want to display.

After displaying your text you must call EndPaint to release the handle.

For example, to display 'Hello World' at screen position 10,10 you could do this:

PAINTSTRUCT ps;

HDC hdc = BeginPaint(hWnd, &ps);

TextOut(hdc,10,10,"Hello World",11);

EndPaint(hWnd, &ps);

Did u know? What is GDI +?

Windows GDI+ is a class-based API for C/C++ programmers. It enables applications to


use graphics and formatted text on both the video display and the printer.

LOVELY PROFESSIONAL UNIVERSITY 209


Windows Programming

Notes 13.1.2 Displaying Pixels

You can drawn single pixels to the screen using the following function:

SetPixel( HDC hdc, int X, int Y, COLORREF crColor);

Again it requires a handle to a device context (HDC) and a screen position. Additionally the
colour you want to set the pixel to can be provided. This needs to be given in a Win32 type
COLORREF. Fortunately, we can use a macro (RGB) to convert from three Red, Green and Blue
values to a COLORREF type. Each colour component can range from 0 to 255.

To display a red pixel at screen co-ordinates 100,100 we would write:

SetPixel(hdc, 100, 100, RGB(255,0,0));

Task In a group of four analyze why GDI can be used in all Windows-based applications.

13.1.3 Drawing Lines

There are a number of functions for drawing lines using GDI. You can use MoveTo and LineTo
to position a pen on the screen and draw a line to another position. You can also use PolyLine,
PolyPolyLine, Arc, etc. To explore which ones are available look in the MSDN help. We will
describe here the use of PolyLine.

PolyLine draws lines between points defined in an array you pass to the function. The function
definition is:

Polyline(HDC hdc, CONST POINT *lppt, int cPoints);

This takes the device handle, an array of points and how many points there are in the array. It
draws lines between each point. POINT is a structure with member variables x and y.

To draw a simple diagonal line we could do this:

POINT pntArray[2];
pntArray[0].x=10;

pntArray[0].y=10;

pntArray[1].x=100;

pntArray[1].y=100;

Polyline(hdc, pntArray, 2);

!
Caution The color and style of the line can be changed by using pens.

13.1.4 Drawing Filled Shapes

You can draw filled rectangles using FillRect and filled ellipses using Ellipse. Also, not covered
here, you can draw filled polygons, pies, rounded rectangles etc. Again look in the MSDN help
for details.

210 LOVELY PROFESSIONAL UNIVERSITY


Unit 13: Windows GDI

To draw a filled ellipse we can use: Notes

BOOL Ellipse(HDC hdc, int nLeftRect, int nTopRect, int nRightRect, int nBottomRect );

This function takes the device context and the screen positions of a rectangle that represents the
bounding rectangle for the ellipse. The ellipse will be drawn to fit in this rectangle.

To draw a filled rectangle we can use:

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


This function takes the device context, a rectangle structure and a brush. The RECT structure
contains member variables left, right, top and bottom. Brushes are described in the next section:
Pens and Brushes.

13.1.5 Pens and Brushes

GDI uses the concept of Pens and Brushes. A Pen defines the style and colour that pixels will be
drawn in while a brush determines the fill colour of shapes. A number of the GDI drawing
functions can be effected by the pen or brush chosen.

Pens

To create a pen we need to obtain a handle to one. This handle is named HPEN, we can keep hold
of this handle during the lifetime of our program but must remember to delete it before exiting.

To create a pen we use the function:

HPEN CreatePen( int fnPenStyle, int nWidth, COLORREF crColor);

This function takes a style, a pen width and a colour. The style must be one of the predefined
styles. The main ones are shown below:

PS_SOLID - Pen is solid.

PS_DASH - Pen is dashed.

PS_DOT - Pen is dotted.


PS_DASHDOT - Pen has alternating dashes and dots.

PS_DASHDOTDOT - Pen has alternating dashes and double dots.

PS_NULL - Pen is invisible.

So to create a solid green pen of 1 pixel width we would write:

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

It is a good idea to create our pens (and brushes) in advance of drawing and then apply them as
required. To apply a pen so future drawing commands use it we must select it. This is known as
selecting it into the device context and is achieved by using SelectObject. One thing we must be
aware of is that when we no longer want to use our pen we need to re-select the old pen. Luckily
SelectObject returns the old pen. So to use our green pen to draw a line we may do this:

// Select our green pen into the device context and remember previous pen

HGDIOBJ oldPen=SelectObject(hdc,greenPen);

// Draw our line

LOVELY PROFESSIONAL UNIVERSITY 211


Windows Programming

Notes Polyline(hdc, pntArray, 2);

// Select the old pen back into the device context

SelectObject(hdc,oldPen);

Brushes

Creating and using Brushes is very similar to pens. We can use CreateSolidBrush to create a
solid coloured brush or CreateBrushIndirect to create a brush with specific styles (like hatched)
or even using a loaded bitmap. You can use a bitmap as a repeating pattern for your brush using
CreatePatternBrush. Here we will describe CreateSolidBrush for the others please look int he
MSDN help file.

HBRUSH CreateSolidBrush( COLORREF crColor)

This is a very simple function that takes the required colour and returns a handle to a brush. We
can use it in much the same way as the pen. To create a blue brush we would write:

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

To use it to fill a rectangle:

RECT rct;

rct.left=10;

rct.right=100;

rct.top=10;

rct.bottom=200;

FillRect(hdc, &rct, blueBrush);

13.1.6 Window Size

When you create a window you can specify its size. However the size of the window does not
always relate to the drawing area as there are menu bars and borders that also take up room.
Additionally the user can simply alter the size of your window at any time. So we need a way of
determining the current drawing area. We do this using the GetClientRect call. This returns a
rectangle defining the area of the window your program (the client) can draw into. You must
pass in the handle to your window and the address of a rectangle that will be filled by the
function.

Example: RECT clientRect;


GetClientRect(hWnd,&clientRect);

13.1.7 Forcing a Redraw

As we have mentioned previously you can only draw your window when Windows tells you to
via a WM_PAINT message. Sometimes you would like to update your window whenever you
want. To do this you have to tell Windows that your window is dirty and needs a redraw. You
can do this by using InvalidateRect. This tells Windows your window is dirty and needs
redrawing. Windows then sends you a WM_PAINT message telling you to draw. InvalidateRect
takes three parameters, the handle to your window, the rectangular area of your window that

212 LOVELY PROFESSIONAL UNIVERSITY


Unit 13: Windows GDI

needs to be redrawn (or NULL for the whole window) and a Boolean indicating if you wish the Notes
window to be cleared first. So the standard call for clearing the whole window is:

InvalidateRect(hWnd,NULL,TRUE);

Self Assessment

Fill in the blanks:

1. To display some text you can use the …………………… function.

2. To obtain the handle you call: BeginPaint, it takes your window handle and a pointer to a
……………………………….. that you have declared.

3. We can use a macro (RGB) to convert from three Red, Green and Blue values to a
…………………………….. type.

4. Additionally the colour you want to set the …………………….. to can be provided.

5. You can use ……………………. and LineTo to position a pen on the screen and draw a line
to another position.

6. …………………… draws lines between points defined in an array you pass to the function.

7. Additionally the user can simply alter the ………………. of your window at any time.

8. You can use a bitmap as a repeating pattern for your brush using ………………………….

9. A ………………….. defines the style and colour that pixels will be drawn in while a brush
determines the fill colour of shapes.

10. The ………………….. structure contains member variables left, right, top and bottom.


Caselet Banking on BlackBerry

T
here's this old joke about two campers who spy a grizzly coming towards them
from afar. One of them immediately takes off his shoes and substitutes them for
runners. "Why are you doing that? You can't outrun that bear even with running
shoes," said his friend, to which he replied, "Who cares about the grizzly? All I have to do
is outrun you."

Employ this logic in the real world, and you see a similar situation with mobile
manufacturers who are busy trying to woo users, and have to keep developers on their
side. Because if you can't attract developers, you won't get any great apps, and without
apps, your smartphone isn't worth the pixels on its screen.

Rise of the Underdog?

In this game, BlackBerry is at a slight disadvantage because it is not perceived to be a big


player, and so has to strive a little harder to keep up.

Pointing this out, Anil Pai, Mobile Security Analyst, TCS, says, "Android and iPhone are
the market leaders, followed by Windows. BlackBerry is in the fourth spot and may pick
up in future." Pai says that the launch of the QNX operating system for BlackBerry in a few

Contd...

LOVELY PROFESSIONAL UNIVERSITY 213


Windows Programming

Notes months, coupled with the security features the manufacturer offers, will make it a viable
alternative to the other three. And while TCS is currently not working on anything for
BlackBerry platform from the security standpoint, he said that the company plans to do
this in the near future. Getting a big software player like TCS to work on its platform is a
big plus for BlackBerry.

This is because the stakes are huge. According to an IDC report released in January 2012,
the world's mobile worker population will reach 1.3 billion by 2015, representing 37.2 per
cent of the total workforce. Asia Pacific (excluding Japan) will see the maximum growth
from around 601.7 million mobile workers in 2010 to 838.7 million in 2015, spurred
primarily by India and China.

Many of them will be carrying smartphones and being the number fourth in this list, one
expects BlackBerry to try that much harder to woo developers because apps hold the key
to smartphone adoption.

Ironing Out the Creases

One of the things that might help BlackBerry could be its native functionality, said Sunil
Mishra, Senior Software Engineer, Creative Commons, who has been developing apps on
both Android and BlackBerry.

"Both are good, but BlackBerry has a richer user interface." Mishra said that he would
continue to develop apps for BlackBerry in spite of his knowledge of Android because, as
he put it, "Android is easy to learn but difficult to debug."

Such news will be music to RIM's ears, which will no doubt want to increase its market
share in India – a tough thing to do if you are not a major player because the market for
smartphones is rather limited in India as of now. In November last year, Gartner said that
while Indian mobile handset sales would reach 231 million units in 2012, an increase of 8.5
per cent over 2011 sales of 213 million units, very few would be smartphones. In fact, in the
first three quarters of the calendar year 2011, smartphone sales in India made up 6 per cent
of total device sales, and this is expected to increase only to 8 per cent in 2012. View this
statistic in a different light, and this translates to about 18.48 million smartphones being
shipped in India in calendar year 2012, with BlackBerry taking a relatively smaller
percentage of sales.
Another big problem with BlackBerry is the total number of apps available. According to
Annie Mathew, Head of Alliances and Developer Relations, India, Research in Motion,
there are about 50,000 apps on BlackBerry's App World, which is a very small number
when compared to Apple, which has at least 5 lakh apps on its App Store. But BlackBerry
is trying to turn around its smaller base by offering a customised service to developers,
she says. Citing an example, she says that when Dhingana, which was launched on the App
Store two years ago, first came to BlackBerry, they had a lot of issues, but BlackBerry's
team helped them to resolve them. "It is important for developers that they should find it
easy to develop apps," she said.

And some developers are finding this to be true. Vineeth Karunakaran, Senior Software
Engineer, USD Global, who has been developing apps for BlackBerry for three years (he
also develops J2ME apps for Nokia and other platforms, besides writing apps for Symbian)
says that he shifted to developing for BlackBerry because of the satisfaction he gets from
the platform. "We are able to do everything we want. It is better than offerings from
competitors," he said.

Contd...

214 LOVELY PROFESSIONAL UNIVERSITY


Unit 13: Windows GDI

Language Barriers Notes

Of course, there is also another issue – programming languages. Once a developer learns
a programming language, he is not always eager to jump from what he knows to what he
doesn't because this involves relearning a language. Karunakaran, who is well-versed
with Java, says that he can't move to iOS because he is required to program it in Objective
C, a language that he is not familiar with. He also has no desire to move to Android, a
platform that he says he doesn't like. "Android has a lot of bugs even with basic features
like phone calls and SMS. I have an Android phone and these bugs are making it difficult
for me to use the phone," he said.

So, is the BlackBerry developer market filled with people who don't like other platforms,
or can't move away for various reasons? Mathew disagrees. "Apple is not the most popular
brand in India. That is why developers want to get on to BlackBerry." Highlighting Indian
players like MakeMyTrip, Naukri and Shaadi, she said, "They first made an appearance on
BlackBerry and only then did they get on other platforms. For developers in India, it is
BlackBerry, Android and iOS, in that order."

13.2 Summary

 GDI stands for Graphics Device Interface. It provides many functions for displaying graphics
in your Windows application.

 GDI uses the concept of Pens and Brushes. A Pen defines the style and colour that pixels
will be drawn in while a brush determines the fill colour of shapes.

 We can use CreateSolidBrush to create a solid coloured brush or CreateBrushIndirect to


create a brush with specific styles (like hatched) or even using a loaded bitmap.

 Sometimes you would like to update your window whenever you want. To do this you
have to tell Windows that your window is dirty and needs a redraw. You can do this by
using InvalidateRect.

13.3 Keywords

GDI: Graphics Device Interface

HDC: Handle to a Device Context

13.4 Review Questions

1. Windows-based applications do not access the graphics hardware directly. Explain.

2. To obtain the handle you call: BeginPaint, it takes your window handle and a pointer to a
PAINTSTRUCT that you have declared. Discuss.

3. You can also use PolyLine, PolyPolyLine, Arc etc. To explore which ones are available
look in the MSDN help. Analyze.

4. A number of the GDI drawing functions can be effected by the pen or brush chosen.
Elaborate.

5. When you create a window you can specify its size. Explain with an example.

LOVELY PROFESSIONAL UNIVERSITY 215


Windows Programming

Notes Answers: Self Assessment

1. TextOut 2. PAINTSTRUCT

3. COLORREF 4. pixel

5. MoveTo 6. PolyLine

7. size 8. CreatePatternBrush

9. Pen 10. RECT

13.5 Further Readings

Books Beginning C: From Novice to Professional, Fourth Edition by Ivor Horton.


C# Programming Language, The (2nd Edition) (Microsoft .NET Development
Series) (Hardcover) by Anders Hejlsberg, Scott Wiltamuth, Peter Golde, Publisher:
Addison-Wesley Professional; 2 edition (June 9, 2006)

CLR via C#, Second Edition (Paperback) by Jeffrey Richter, Publisher: Microsoft
Press; 2nd edition (February 22, 2006)

Essential C# 2.0 (Microsoft .NET Development Series) (Paperback) by Mark


Michaelis, Publisher: Addison-Wesley Professional (July 13, 2006)

Expert C# 2005 Business Objects, Second Edition by Rockford Lhotka.

Pro C# 2005 and the .NET 2.0 Platform, Third Edition by Andrew Troelsen.

Programming in the Key of C# (Paperback) by Charles Petzold, Publisher:


Microsoft Press; 1 edition (July 30, 2003)

Online links http://msdn.microsoft.com/en-us/library/dd145203(v=vs.85).aspx


http://en.wikipedia.org/wiki/Graphics_Device_Interface

216 LOVELY PROFESSIONAL UNIVERSITY


Unit 14: Text and Graphics Output

Unit 14: Text and Graphics Output Notes

CONTENTS

Objectives

Introduction

14.1 Character Mode vs Graphic Mode

14.1.1 Character Mode

14.1.2 Graphic Mode

14.2 The Device Context

14.3 Text Output

14.4 WM_PAINT Message

14.5 Changing the Device Context

14.6 Device Context Settings

14.6.1 Setting and Retrieving the Device Context Brush Color Value

14.6.2 Setting the Pen or Brush Color

14.7 Graphics Output

14.7.1 Line and Shape Controls

14.7.2 The Image Box and the Picture Box

14.8 Animated Graphics

14.9 The Peek Message [] Loop

14.9.1 The GetMessage()

14.9.2 A New Function, PeekMessage()

14.10 Summary

14.11 Keywords

14.12 Review Questions

14.13 Further Readings

Objectives

After studying this unit, you will be able to:

 Understand Character mode vs. Graphic Mode

 Discuss the concept of Device Context

 Discuss Text output and WM_PAINT message

 Understand Graphics Output

 Illustrate the concept of changing the device context

LOVELY PROFESSIONAL UNIVERSITY 217


Windows Programming

Notes  Discuss Animated Graphics

 Understand the function of Peek Message [] Loop

Introduction

In this unit, you will understand various concepts related to text and graphics output such as
Character mode vs. Graphic Mode, Device Context, Text output, WM_PAINT message, Graphics
Output, Animated Graphics, etc.

14.1 Character Mode vs. Graphic Mode

14.1.1 Character Mode

Many video adapters support several different modes of resolution. All such modes are divided
into two general categories: character mode (also called text mode) and graphics mode. In character
mode, the display screen is treated as an array of blocks, each of which can hold one ASCII
character. Of the two modes, character mode is much simpler. Programs that run in character
mode generally run much faster than those that run in graphics mode, but they are limited in the
variety of fonts and shapes they can display. Programs that run entirely in character mode are
called character-based programs.

14.1.2 Graphic Mode

In graphics mode, the display screen is treated as an array of pixels, with characters and other
shapes formed by turning on combinations of pixels. Of the two modes, graphics mode is the
more sophisticated. Programs that run in graphics mode can display an unlimited variety of
shapes and fonts, whereas programs running in character mode are severely limited. Programs
that run entirely in graphics mode are called graphics-based programs.

Self Assessment

Fill in the blanks:

1. Programs that run entirely in character mode are called ......................... programs.

2. In graphics mode, the display screen is treated as an array of ......................... .

14.2 The Device Context

A device context is a Windows data structure containing information about the drawing attributes
of a device such as a display or a printer. All drawing calls are made through a device-context
object, which encapsulates the Windows APIs for drawing lines, shapes, and text. Device contexts
allow device-independent drawing in Windows. Device contexts can be used to draw to the
screen, to the printer, or to a metafile.

CPaintDC objects encapsulate the common idiom of Windows, calling the BeginPaint function,
then drawing in the device context, then calling the EndPaint function. The CPaintDC constructor
calls BeginPaint for you, and the destructor calls EndPaint. The simplified process is to create
the CDC object, draw, and destroy the CDC object. In the framework, much of even this process
is automated. In particular, your OnDraw function is passed a CPaintDC already prepared
(via OnPrepareDC), and you simply draw into it. It is destroyed by the framework and the

218 LOVELY PROFESSIONAL UNIVERSITY


Unit 14: Text and Graphics Output

underlying device context is released to Windows upon return from the call to your OnDraw Notes
function.

CClientDC objects encapsulate working with a device context that represents only the client
area of a window. The CClientDC constructor calls the GetDC function, and the destructor calls
the ReleaseDC function. CWindowDC objects encapsulate a device context that represents the
whole window, including its frame.

Did u know? CMetaFileDC objects encapsulate drawing into a Windows metafile.

!
Caution In contrast to the CPaintDC passed to OnDraw, you must in this case call
OnPrepareDC yourself.

Task Illustrate the function of CClientDC objects.

Self Assessment

Fill in the blanks:


3. A ......................... is a Windows data structure containing information about the drawing
attributes of a device such as a display or a printer.
4. The ......................... constructor calls BeginPaint for you, and the destructor calls EndPaint.
5. CWindowDC objects encapsulate a device context that represents the whole window,
including its frame.

14.3 Text Output


Text Output
create_interactive_index In a Textflow define some terms to be indexed and create a
sorted index from the indexed terms.
vertical_alignment_in_fitbox Control the vertical alignment of text in the fitbox.
keep_lines_together Control the lines kept together on the page.
drop_caps Create an initial drop cap at the beginning of some text.
distance_between_paragraphs Control the distance between adjacent paragraphs.
avoid_linebreaking Create a Textflow and define various options for line breaking.
bulleted_list Output numbered and bulleted lists.
continue_note_after_text Insert a dot sequence automatically at the end of a textflow
fitbox after the last word which can be showed together with
the dots completely inside the fitbox.
current_text_position Demonstrate how the current text position can be used to
output simple text, text lines, or Textflows next to one another.
dot_leaders_with_tabs Use leaders to fill the space defined by tabs between left-
aligned and right-aligned text, such as in a table of contents.
footnotes_in_text Create footnotes (superscript text) in a Textflow provided with
links to jump to the footnote text.
image_as_text_fill_color Create outline text and fill the interior of the glyphs with an Contd...
image.
invisible_text Output invisible text on top of an image.
leaders_in_textline Use dot leaders to fill the space between text and a page
LOVELY PROFESSIONAL UNIVERSITY 219
number such as in a table of contents.
numbered_list Output numbered lists with the numbers left- or right-aligned.
process_utf8 Read text in the UTF-8 format and output it.
rotated_text Create text output which does not run horizontally, but at
some angle.
continue_note_after_text Insert a dot sequence automatically at the end of a textflow
fitbox after the last word which can be showed together with
the dots completely inside the fitbox.
current_text_position Demonstrate how the current text position can be used to
output simple text, text lines, or Textflows next to one another.
Windows Programming dot_leaders_with_tabs Use leaders to fill the space defined by tabs between left-
aligned and right-aligned text, such as in a table of contents.
footnotes_in_text Create footnotes (superscript text) in a Textflow provided with
links to jump to the footnote text.
Notes
image_as_text_fill_color Create outline text and fill the interior of the glyphs with an
image.
invisible_text Output invisible text on top of an image.
leaders_in_textline Use dot leaders to fill the space between text and a page
number such as in a table of contents.
numbered_list Output numbered lists with the numbers left- or right-aligned.
process_utf8 Read text in the UTF-8 format and output it.
rotated_text Create text output which does not run horizontally, but at
some angle.
shadowed_text Create a shadowed text line with the shadow option of
fit_textline.
simple_stamp Create a stamp across the page which runs diagonally from one
edge to the other.
starter_textflow Create multi-column text output which may span multiple
pages.
starter_textline Demonstrate various options for placing a text line.
tabstops_in_text Create a simple multi-column layout using tab stops.
text_as_clipping_path Output text filled with an image.
text on a path Create text on a path.
text_on_color Place a text line and a Textflow on a colored background.
text_with_image_clipping_path Use the clipping path from a TIFF or JPEG image to shape text
output.
transparent_part_of_text Use gstate in Textflow, e.g. for transparency/opacity
transparent_text Create some transparent text.
underlined_text Create underlined text.
weblink_in_text Create a Textflow and integrate colorized Web links in the text.
wrap_text_around_images Place images within a Textflow.
wrap_text_around_polygons Use arbitrary polygons as wrapping shapes for text to wrap
around.

These text outputs are used in Windows GDI which is explained in Unit 13.

Self Assessment

Fill in the blank:

6. ......................... is used to create an initial drop cap at the beginning of some text.

14.4 WM_PAINT Message

The WM_PAINT message is sent when the system or another application makes a request to
paint a portion of an application’s window. The message is sent when the UpdateWindow or
RedrawWindow function is called, or by the DispatchMessage function when the application
obtains a WM_PAINT message by using the GetMessage or PeekMessage function.

A window receives this message through its WindowProc function.


LRESULT CALLBACK WindowProc(
HWND hwnd,
UINT uMsg,

220 LOVELY PROFESSIONAL UNIVERSITY


Unit 14: Text and Graphics Output

WPARAM wParam, Notes


LPARAM lParam
);

Parameters

wParam: This parameter is not used.

lParam: This parameter is not used.

Return Value

An application returns zero if it processes this message.

The WM_PAINT message is generated by the system and should not be sent by an application.
To force a window to draw into a specific device context, use the WM_PRINT or
WM_PRINTCLIENT message. Most common controls support the WM_PRINTCLIENT
message.

!
Caution This requires the target window to support the WM_PRINTCLIENT message.

The DefWindowProc function validates the update region. The function may also send the
WM_NCPAINT message to the window procedure if the window frame must be painted and
send the WM_ERASEBKGND message if the window background must be erased.

The system sends this message when there are no other messages in the application’s message
queue. DispatchMessage determines where to send the message; GetMessage determines which
message to dispatch. GetMessage returns the WM_PAINT message when there are no other
messages in the application’s message queue, and DispatchMessage sends the message to the
appropriate window procedure.

Notes A window may receive internal paint messages as a result of calling RedrawWindow
with the RDW_INTERNALPAINT flag set. In this case, the window may not have an
update region. An application should call the GetUpdateRectfunction to determine whether
the window has an update region. If GetUpdateRect returns zero, the application should
not call the BeginPaint and EndPaint functions.

Task What does dispatchMessage signify?

Self Assessment

Fill in the blanks:

7. The ......................... message is sent when the system or another application makes a request
to paint a portion of an application’s window.

8. ......................... determines where to send the message.

LOVELY PROFESSIONAL UNIVERSITY 221


Windows Programming

Notes 14.5 Changing the Device Context

The following functions are used with device contexts.

Function Description

CancelDC Cancels any pending operation on the specified device context.


ChangeDisplaySettings Changes the settings of the default display device to the specified
graphics mode.
ChangeDisplaySettingsEx Changes the settings of the specified display device to the specified
graphics mode.
CreateCompatibleDC Creates a memory device context compatible with the specified
device.
CreateDC Creates a device context for a device using the specified name.
CreateIC Creates an information context for the specified device.
DeleteDC Deletes the specified device context.
DeleteObject Deletes a logical pen, brush, font, bitmap, region, or palette, freeing
all system resources associated with the object.
DeviceCapabilities Retrieves the capabilities of a printer device driver.
DrawEscape Provides drawing capabilities of the specified video display that are
not directly available through the graphics device interface.
EnumDisplayDevices Retrieves information about the display devices in a system.
EnumDisplaySettings Retrieves information about one of the graphics modes for a display
device.
EnumDisplaySettingsEx Retrieves information about one of the graphics modes for a display
device.
EnumObjects Enumerates the pens or brushes available for the specified device
context.
EnumObjectsProc An application-defined callback function used with
the EnumObjects function.
GetCurrentObject Retrieves a handle to an object of the specified type that has been
selected into the specified device context.
GetDC Retrieves a handle to a display device context for the client area of a
specified window or for the entire screen.
GetDCBrushColor Retrieves the current brush color for the specified device context.
GetObject Retrieves information for the specified graphics object.
GetObjectType Retrieves the type of the specified object.
GetStockObject Retrieves a handle to one of the stock pens, brushes, fonts, or
palettes.
ReleaseDC Releases a device context, freeing it for use by other applications.
ResetDC Updates the specified printer or plotter device context using the
specified information.
SelectObject Selects an object into the specified device context.
SetDCBrushColor Sets the current device context brush color to the specified color
value.
SetDCPenColor Sets the current device context pen color to the specified color value.
SetLayout Sets the layout for a device context.

222 LOVELY PROFESSIONAL UNIVERSITY


Unit 14: Text and Graphics Output

Self Assessment Notes

Fill in the blank:

9. ......................... changes the settings of the default display device to the specified graphics
mode.

14.6 Device Context Settings

14.6.1 Setting and Retrieving the Device Context Brush Color Value

The following example shows how an application can retrieve the current DC brush color by
using the SetDCBrushColor and the GetDCBrushColor functions

Example:
SelectObject(hdc,GetStockObject(DC_BRUSH));
SetDCBrushColor(hdc, RGB(00,0xff;00);
PatBlt(0,0,200,200,PATCOPY)
SetDCBrushColor(hdc,RGB(00,00,0xff);
PatBlt(0,0,200,200,PATCOPY);

14.6.2 Setting the Pen or Brush Color

The following example shows how an application can change the DC pen color by using the
GetStockObject function or SetDCPenColor and the SetDCBrushColorfunctions.

Example:
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM
lParam)
{
int wmId, wmEvent;
PAINTSTRUCT ps;
HDC hdc;

switch (message)
{
case WM_COMMAND:
wmId = LOWORD(wParam);
wmEvent = HIWORD(wParam);
// Parse the menu selections:
switch (wmId)
{
case IDM_ABOUT:
DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);

LOVELY PROFESSIONAL UNIVERSITY 223


Windows Programming

Notes break;
case IDM_EXIT:
DestroyWindow(hWnd);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
break;
case WM_PAINT:

{
hdc = BeginPaint(hWnd, &ps);
// Initializing original object
HGDIOBJ original = NULL;

// Saving the original object


original = SelectObject(hdc,GetStockObject(DC_PEN));

// Rectangle function is defined as...


// BOOL Rectangle(hdc, xLeft, yTop, yRight, yBottom);

// Drawing a rectangle with just a black pen


// The black pen object is selected and sent to the current
device context
// The default brush is WHITE_BRUSH
SelectObject(hdc, GetStockObject(BLACK_PEN));
Rectangle(hdc,0,0,200,200);

// Select DC_PEN so you can change the color of the pen with
// COLORREF SetDCPenColor(HDC hdc, COLORREF color)
SelectObject(hdc, GetStockObject(DC_PEN));

// Select DC_BRUSH so you can change the brush color from the
// default WHITE_BRUSH to any other color
SelectObject(hdc, GetStockObject(DC_BRUSH));

// Set the DC Brush to Red


// The RGB macro is declared in “Windowsx.h”
SetDCBrushColor(hdc, RGB(255,0,0));

// Set the Pen to Blue

224 LOVELY PROFESSIONAL UNIVERSITY


Unit 14: Text and Graphics Output

SetDCPenColor(hdc, RGB(0,0,255)); Notes

// Drawing a rectangle with the current Device Context


Rectangle(hdc,100,300,200,400);

// Changing the color of the brush to Green


SetDCBrushColor(hdc, RGB(0,255,0));
Rectangle(hdc,300,150,500,300);

// Restoring the original object


SelectObject(hdc,original);

// It is not necessary to call DeleteObject to delete stock


objects.
}

break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}

Self Assessment

Fill in the blank:

10. An application can retrieve the current DC brush color by using the SetDCBrushColor
and the ......................... functions.

14.7 Graphics Output

Graphics is a very important part of visual basic programming as an attractive interface will be
appealing to the users. In the old BASIC, drawing and designing graphics are considered as
difficult jobs, as they have to be programmed line by line in a text-based environment. However,
in Visual Basic, these jobs have been made easy. There are four basic controls in VB that you can
use to draw graphics on your form: the line control, the shape control, the image box and the
picture box

14.7.1 Line and Shape Controls

To draw a straight line, just click on the line control and then use your mouse to draw the line on
the form. After drawing the line, you can then change its color, width and style using the

LOVELY PROFESSIONAL UNIVERSITY 225


Windows Programming

Notes BorderColor, BorderWidth and BorderStyle properties. Similarly, to draw a shape, just click on
the shape control and draw the shape on the form.

Did u know? The default shape is a rectangle, with the shape property set at 0.

You can change the shape to square, oval, circle and rounded rectangle by changing the shape
property’s value to 1, 2, 3 4, and 5 respectively. In addition, you can change its background color
using the BackColor property, its border style using the BorderStyle property, its border color
using the BorderColor property as well its border width using the BorderWidth property.

14.7.2 The Image Box and the Picture Box

Using the line and shape controls to draw graphics will only enable you to create a simple
design. In order to improve the look of the interface, you need to put in images and pictures of
your own. Fortunately, there are two very powerful graphics tools you can use in Visual Basic
which are the image box and the picture box.

To load a picture or image into an image box or a picture box, you can click on the picture
property in the properties window and a dialog box will appear which will prompt the user to
select a certain picture file. You can also load a picture at runtime by using the LoadPicture ( )
method. The syntax is

Image1.Picture= LoadPicture(“C:\path name\picture file name”) or

picture1.Picture= LoadPicture(“C:\path name\picture name”)

Example: The following statement will load the grape.gif picture into the image box.
Image1.Picture= LoadPicture(“C:\My Folder\VB program\Images\grape.gif”)

Example: In this example, each time you click on the ‘change pictures’ button as shown
in Figure below, you will be able to see three images loaded into the image boxes. This program
uses the Rnd function to generate random integers and then uses the LoadPicture method to load
different pictures into the image boxes using the If…Then…Statements based on the random
numbers generated. The output is shown in Figure below

226 LOVELY PROFESSIONAL UNIVERSITY


Unit 14: Text and Graphics Output

Dim a, b, c As Integer Notes

Private Sub Command1_Click ()

Randomize Timer

a = 3 + Int(Rnd * 3)

b = 3 + Int(Rnd * 3)

c = 3 + Int(Rnd * 3)

If a = 3 Then
Image1(0).Picture = LoadPicture(“C:\My Folder\VB program\Images\grape.gif”)

End If

If a = 4 Then

Image1(0).Picture = LoadPicture(“C:\My Folder\VB program\Images\cherry.gif”)

End If

If a = 5 Then

Image1(0).Picture = LoadPicture(“C:\My Folder\VB program\Images\orange.gif”)

End If

If b = 3 Then

Image1(1).Picture = LoadPicture(“C:\My Folder\VB program\Images\grape.gif”)

End If

If b = 4 Then

Image1(1).Picture = LoadPicture(“C:\My Folder\VB program\Images\cherry.gif”)

End If

If b = 5 Then

Image1(1).Picture = LoadPicture(“C:\My Folder\VB program\Images\orange.gif”)

End If

If c = 3 Then

Image1(2).Picture = LoadPicture(“C:\My Folder\VB program\Images\grape.gif”)

End If

If c = 4 Then

Image1(2).Picture = LoadPicture(“C:\My Folder\VB program\Images\cherry.gif”)

End If

If c = 5 Then

Image1(2).Picture = LoadPicture(“C:\My Folder\VB program\Images\orange.gif”)

End If

End Sub

LOVELY PROFESSIONAL UNIVERSITY 227

You might also like