Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | ASP.NET 2.0 Tutorials | Web Services | How Do I...? | Class Browser | WPF Quick Starts | Advertise with Us
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Team Foundation Server Hosting
Search :       Advanced Search »
Home » MFC » Device Contexts and Graphical User Interface

Device Contexts and Graphical User Interface

In this Article I will walk you through GDI and DC in MFC. Later we will create an example that uses Pen and Brushes on PaintDC

Author Rank :
Page Views : 1457
Downloads : 5
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
MFCGDI.zip
 
 
Nevron Gauge for SharePoint
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 


Note: This Article demonstrates the Example using Visual Studio 2003. If you have Visual Studio 6.0, the steps are different that I leave it to you to explore.

 

1. GDI and DC

 

GDI stands for Graphical Device Interface. It aids drawing on the Windows using the DC. DC stands for Device Contexts. Device context is kind of Drawing Board with some set of characteristics assigned to it. These characteristics involve how the line drawings should appear and how much is the thickness of the line (Pen), how the texts will appear (Font), How do you display images (Bitmap), How do you draw filled surfaces (Brush) etc. The equipments (Pen, Brush, Font etc) used to control the drawing behavior on the drawing board (DC) are called GDI objects.

 

Here we will create an example that uses the Pen and Brush GDI objects and draw something on the client area. Also we will see the messages that need to be handled. Messages in Windows programming world are nothing but a kind of event that will be sent to a windows. Somebody will send a message using SendMessage or Postmessage and some code will define a handler function to respond.

 

2. Types of Device Contexts


MFC framework supports four different types of device contexts. The types are:

  • CClientDC
  • CPaintDC
  • CWindowsDC
  • CMetaFileDC

 

All the above shows a class in the MFC Framework to deal with different type of DCs. Before Knowing them consider the below picture that shows a sample window [Notepad]:

 

Pic1.JPG

 

The window may have a Frame window (Combination of Menu, Toolbar), Status Window (Status bars) and the Client Window. In the above sample the notepad has Frame Window and Client Window. Whatever we type goes to the client window and based on the Font Object the letters are getting drawn.

 

Let us say you want to draw circle on the client area, the choice is either CClientDC or CPaintDC. So both these device contexts are used to perform drawing on the Windows Client Area. With WindowDC you can draw on anywhere in the window and that means you can draw an Traffic button on your Menu Bar (FrameWindow) and Put some fancy texts on your status bar. MetaFileDC are used to record your GDI drawings in a file for later playback.

 

Note: CPaintDC can be used only inside the OnPaint() message handler. CClientDC can be in any function except OnPaint().

 

 

3. Create SDI application

 

1) Open Visual studio 2005

2) Select Visual C++ as Project Types

3) Select MFC Application in the Template List at the right hand side

4) After selecting the Name and Location, click the OK button

5) In the Wizard click the application type link on the Left side pane. Use the below picture as reference to set the options:

 

Pic2.JPG

 

6) Click the Finish button. If you need, take a walk by clicking the next and click finish at the End.

7) Right click the project name and select build. Click the start-debugging button on the tool bar. The application is shown below:

 

Pic3.JPG

 

Now you had created a SDI (Single Document Interface) application without Document and View Architecture. I will write about document and View architecture in a different write-up. Here, we are going to draw something on the Client Area of the above window. First, we will set the Background color to Black and then start our drawing.

 

 

4. Classes created by the Framework

 

Now look at the class view. It shows classes created by the application wizard. To look at the class view, click the class view tab on the right/left side pane. If it is not available Access it from the View>Class view. Don't have class view menu item under view!! What a Bad luck?! Follow the steps below:

1) Click the menu item Tools->Customize

2) In the categories list, select View

3) Drag the Class View from Commands List to a tool bar or View menu popup

4) Close the customize dialog and click the class view now

 

The Classes created by the app wizard is shown below:

 

Pic3a.JPG

CGDIApp is the application class. The object of this will get created in the Code Segment of the memory when the application is launched. That means the wizard declares the CGDIApp as global. Search for CGDIApp theApp;

 

CChildView is derived from the view class and it is responsible for making drawing on the ClientWindow (If you forgot it, have a look at the notepad picture). In the example we are going to write code here.

 

CMainFrame class derived from the CFrameWnd. This class is responsible for hosting the Menu bar, Toolbar, dialog bar etc. Our application by default displays a toolbar and menu bar.

 

5. Changing the background

 

To change the background color of the client window we need to handle the message WM_ERASEBKGND. To handle the message first open the class wizard. Follow the steps below to get a handler for the WM_ERASEBKGND.

1) Right click the CChildview

2) Select property from the context menu that appeared

3) In the property window select the Message button

 

Pic4.JPG

 

4) Search for the Message on the left WM_ERASEBKGND side list of message. Here WM_ stands for window message.

5) Select the first item (Add OnEraseBKGnd) in the drop down that appears next to Message that you had selected.

6) This will bring you to the code editor and we are going to the set the background for the client area of the application here.

 

In the handler first we will get the Client Window dimension in the form of RECT structure wrapped by the Built-in class CRect. Below is the code for this:

 

//GDI 001_01: Get the client area dimention in the form of Rect

CRect drawing_area;

GetClientRect(&drawing_area);

 

Next we need a brush and a color that the brush uses. CBrush GDI object is created using the COLORREF value. This COLORREF value is DWORD. That means, a 32-bit value that stores the color in the form Red, Green, Blue and Alpha. Each component takes 8 bits. MFC provides a RGB macro which combines the Red, Green, Blue values (Alpha is set to default – No transparent) and Packs it into 32-bit value to form a DOWRD. So we can use the RGB macro to get the Color combination from Red, green and blue and assign it to the COLORREF. Below is the code that creates a color brush:

 

//GDI 001_02: Prepare a brush for Background painting

COLORREF backcolor = RGB(0,0,0);

CBrush brush_back_ground(backcolor);

 

Next we use FillRect function to paint the entire client window by the brush that we created. Code is given below:

 

//GDI 001_03: Use the pDC object passed-in to draw the Rectangle with

//filled color.

pDC->FillRect(&drawing_area, &brush_back_ground);

 

As we handled the background painting do not allow the call for base class to draw a default white background. Code:

 

//GDI 001_04: Remove CWnd:OnEraseBkGnd and return true.

// We do handled the message and take responsibility of how to erase the

// background

return TRUE;

 

The above specified 4 code snippets sets the background for the window. The message WM_ERASEBKGND will be sent whenever a window requires a re-drawing. The redraw for a window is required in the following scenario as I know:

1) When the Window is moved.

2) When the window is resized.

3) When the Window is maximized.

4) When a overlapping window moved.

5) When a overlapping window resized.

6) When a overlapping disappeared (Closed or Minimized)

 

 

If you run the application at this stage the it will look like below:

 

Pic5.JPG

 

6. Making the drawing using Pen and Brush

 

6.1) If you browse the CChildView implementation file, you will find a function called OnPaint. This is actually handler for the WM_PAINT message provided by the application wizard. Also the wizard already created Device Context instant of type CPaintDC ready to use. So let us start our drawing using the CPaintDC object.

 

First we ask the PaintDC to select a white pen from the stock pool and draw a line on the black background that we already set. Call to the function SelectStockObject will allow the dc to select any GDI object available in the default stock pool. We do used this function to select a white pen to the device context. Note at the same time we are storing the pen that was used before. Whenever you select a GDI object to the device context, it will return the object similar object (Pen in the first code snipped). The returned object is used to re-store the default GDI used by the DC.

 

Next, we asked the device context move to particular location by making a call to MoveTo function. The function LineTo will specify the End Point and joint the Start point specified by the MoveTo by drawing a line using the Pen currently selected into the device context. Our first code snippet draws a line in the client window. Below is the code snippet:

 

//GDI 002_1: First Let us Draw a Line. As the background color is black

//We need to create a pen with white color.

CPen * oldPen;

CBrush * oldBrush;

oldPen = (CPen *) dc.SelectStockObject(WHITE_PEN);

dc.MoveTo(5,10);

dc.LineTo(80, 10);

dc.SelectObject(oldPen);

 

6.2) In this code snippet a solid pen with thickness of 3 is created. Also we specified that the color of the thick pen is green using the RGB macro. Now when you draw the line it appears thicker than the previous white pen. Below is code:

 

//GDI 002_2: Create custom pen with different Line thickness.

CPen thick_pen(PS_SOLID, 3, RGB(0,255,0));

oldPen = dc.SelectObject(&thick_pen);

dc.MoveTo(5, 20);

dc.LineTo(80,20);

dc.SelectObject(oldPen);

 

6.3) After this green thick line, a 3d rectangle is drawn. The rectangle will appear in 3d based on the color you specify. For a simple example I created a rectangle in paintbrush. First I set the background color to gray. Then top and left line are drawn in white color. Bottom and right lines are drawn in black color. Look the screen shot below, It looks like a push button, Right?

 

Pic6.JPG

 

This is how windows create a button, and when you press the button windows will replace all the 4 lines in same color. Below is code that we used to draw a 3d rectangle:

 

//GDI 002_3: Create a Rectangle now

dc.Draw3dRect(5,30,80,70, RGB(255,255,255), RGB(120,120,120));

 

6.4) In the below code snippet, we are creating the brush object. Pen is for drawing the lines and brush is for painting the closed surfaces. Now we are going to draw the rectangle filled by some specified color by the brush that we cerate. When we are creating the brush a COLORREF value is passed to its constructor. Then the brush is selected to the device context before drawing the rectangle. If you do not want to fill the rectangle then a NULL brush should be used.

 

//GDI 002_4: Create a Brush that we can use for filling the

// closed surfaces

CBrush brush(RGB(255,0,255));

oldBrush = dc.SelectObject(&brush);

dc.Rectangle(5,110,80,140);

dc.SelectObject(oldBrush);

 

6.5) The below code snipped makes a call to FillRect and uses a Hatch Brush. I hope a explanation not required as you gained some hands-on on the previous code snippets. You can refer MSDN for the CDC class to know more drawing functions and you can use those efficiently by using the Pen and Brush GDI objects. I had not covered other GDI objects here.

 

//GDI 002_5: Hatch Brush is useful to apply a pattern in stead

//of solid fill color

CBrush* hatBrush = new CBrush();

hatBrush->CreateHatchBrush(HS_CROSS, RGB(255,0,255));

oldBrush = dc.SelectObject(hatBrush);

dc.FillRect(new CRect(5,160,80,190), hatBrush);

dc.SelectObject(oldBrush);

 

Below is the Screen shot of what we draw in the Client Window:

 

Pic7.JPG

 

Note: The attached application is created in Visual studio dot net 2003. If you have latest version say "Yes" to the conversion UI that appears.

 

 

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Sivaraman Dhamodaran

Sivaraman Dhamodaran is a System Engineer. He has over 9 years of experience in IT Industries. He has come across Vc++ & MFC Frame Work, Dot.Net technologies. Oracle and SQL Server.
He mostly worked on Desktop database applications, GSM Compatible Modems, Biometric devices and Graphics technologies

Blog: http://sivaramand.blogspot.com/

Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Team Foundation Server Hosting
Become a Sponsor
 Comments
NOTE : by Mohammad On November 29, 2011
very good... please visit our links... //SNAKE GAME : http://www.dotnetheaven.com/UploadFile/m-mirshahi/advanced-snake-game/ //BREAK GAME http://www.dotnetheaven.com/UploadFile/m-mirshahi/break-game/ //TEST YOUR MEMORY http://www.dotnetheaven.com/UploadFile/m-mirshahi/iq-game-test-your-memory/ //SAMPLE ANTI VIRUS http://www.dotnetheaven.com/uploadfile/m-mirshahi/kernel-remover-an-antivirus/default.aspx VERY THANKS...
Reply | Email | Modify 

 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.