Google Ads

Thursday, December 3, 2009

PROGRAMMING MODEL

WINDOWS PROGRAMMING MODEL



Message processing:


 When writing MS – DOS program the only required function is main.

 When windows operating system launches a program, it calls WinMain function.

 Its task is to create the application’s main window which has its own code to process messages that windows sends to it.

 Windows based program processes user input via messages from the operating system.

 For example
 WM_CREATE message is sent when a window is being created.
 WM_LBUTTONDOWN message is sent when the user presses the left mouse button.
 WM_CHAR message is sent when the user types a character.
 WM_CLOSE message is sent when the user closes the window.

Windows Graphics Device Interface:

 Windows provides a layer of abstraction called graphics device interface.

 Instead of addressing the hardware, program calls the GDI functions that reference a data structure called a device context.

 Windows maps the device context structure to a physical device and issues appropriate input / output instructions.

Resource Based Programming:

 In windows the data is stored in a resource file using a number of established format.

 The linker combines the binary resource file with the C++ compiler’s output to generate an executable program.

 Resource files can include bitmaps, icons, menu definitions, dialog based layouts and strings.

Dynamic Link Libraries:

 Windows allows dynamic linking, means that specially constructed libraries can be loaded and linked at runtime.

 Multiple applications can share dynamic link libraries which saves memory and disk space.

 DLL increases program modularity – since it can be compiled and tested separately.

AppWizard:

 Is a code generator that creates a workspace frame of a windows application with features, class names and source code file names.

ClassWizard:

 Is a program that’s accessible from visual C++ view menu.





Application Framework:

 Is an integrated collection of object oriented software components that offers all that needed for a generic application.

 It defines the structure of the program.

 By convention, MFC library class names begin with the letter C.

View:
 A view is an ordinary window that the user can size, move and close in the same way as any other windows – based application window.
 From the programmer’s angle, a view is a C++ object of a class derived from the MFC library CView class.

Single Document Interface (SDI):
 An SDI application has only one window, only one document can be loaded at a time. Notepad is an example for single document interface.

Multiple Document Interface (MDI):
 An MDI application has multiple child windows, each corresponds to an individual document. Microsoft word is an example for MDI.

VIEW WINDOW



DRAWING INSIDE THE VIEW WINDOW

OnDraw member function:

Ø Is a virtual member function of the CView class that the application framework calls every time the view window needs to be repainted.

Windows device context:

Ø Windows doesn’t allow direct access to the display hardware but communicates through an abstraction called a “device context” that is associated with the window.

Ø In the MFC library, the device context is a C++ object of class CDC that is passed as a parameter to OnDraw function.

Steps to build the application:

1.Run AppWizard to generate SDI application source code.

Ø Choose New from visual C++ File menu & then click Projects tab in the resulting New dialog box.

Ø Make sure that MFC AppWizard (exe) is selected and specify the path in the Location textbox finally specify Project Name and click OK.

Ø In the sequence of AppWizard screens select the following:

v Single Document Interface.

v Accept the default in the next four screens.

v In the last screen check the project name, class name and click Finish.

v It displays the New Project Information dialog box, click OK button.

Ø The AppWizard starts to create application’s subdirectory and a series of files in that subdirectory.


FILE

DESCRIPTION

Filename.dsp

A project file that allows Visual C++ to build the application.

Filename.dsw

A workspace file that contains a single entry for the .dsp file.

Filename.rc

An ASCII resource script file.

filenameView.cpp

A view class implementation file that contains class member functions.

filenameView.h

A view class header file that contains the class declaration.

Filename.opt

A binary file that tells Visual C++ which files are open for this project and how the windows are arranged. (not created until project is saved.

Readme.txt

A text file that explains the purpose of generated files.

Resource.h

A header file that contains #define constant declaration.



2. Edit the OnDraw function in the filenameView.cpp:

Ø Find the AppWizard generated OnDraw function in View.cpp and add the following code.

void CfilenameView::OnDraw(CDC* pDC)

{

CfilenameDoc* pDoc = GetDocument();

ASSERT_VALID(pDoc);

pDC->TextOut(0,0,”Hello World!”); // prints in default font & //size, top left corner.

pDC->SelectStockObject(GRAY_BRUSH); // selects a brush for //the circle interior.

pDC->Ellipse(CRect(0,20,100,120)); // draws a gray circle 100 //units in diameter.

}

3. Compile & test the file.




PROGRAM TO HANDLE BASIC EVENTS

PROGRAM TO HANDLE BASIC EVENTS

MESSAGE MAP,
SAVING THE VIEW’S STATE,
INITIALIZING A VIEW CLASS DATA MEMBERS.



Message map:

 When the user presses the left mouse button in a view window, windows sends a message “WM_LBUTTONDOWN” to that window.

 If the program needs to take an action in response to WM_LBUTTONDOWN, view class must have a member function that looks like:

Void CMyView::OnLButtonDown(UINT nFlags, CPoint point)
{
// event processing code here
}

 Class header file must also have the prototype:

afx_msg void OnLButtonDown (UINT nFlags, CPoint point);

the afx_msg is a “no-op” that alerts that this is a prototype for a message map function.

Saving the View’s state:

 The view’s OnDraw function draws an image based on the view’s current state and user actions can alter that state.

 Two view class members used often are m_rectEllipse and m_nColor.

 m_rectEllipse is an object of class CRect, which holds the current bounding rectangle of an ellipse.

 m_nColor is an integer that holds the current ellipse color value.

 By convention, MFC library nonstatic class data member names begin with m_.

Initializing a view class data member:

 The most efficient place to initialize a class data member is in the constructor:

CMyView::CMyView:m_rectEllipse(0,0,200,200)
{
………..
}

Steps to create the application:

1. Run AppWizard to create second application.
2. Add the m_rectEllipse and m_nColor data members to secondView.
 In the workspace window set to ClassView, right click the secondView class, select Add Member variable and then insert the data members:
private:
CRect m_rectEllipse;
int m_nColor;
3. Use ClassWizard to add a secondView class message handles.
 Choose ClassWizard by right-click on the source window.
 Select
Class Name: secondView
Object ID: SecondView
Messages: WM_LBUTTONDOWN (double-click)

the OnLButtonDown function name should appear in the Member functions list box.

4. Edit the OnLButtonDown code in secondView.cpp.

 Click the edit code button in the ClassWizard and the code here:

void secondView::OnLButtonDown (UINT nFlags, CPoint point)
{
if (m_rectEllipse.PtInRect(point))
{
if (m_nColor == GRAY_BRUSH)
{
m_nColor = WHITE_BRUSH;
}
else
{
m_nColor = GRAY_BRUSH;
}
InvalidateRect (m_rectEllipse);
}
}







5. Edit the constructor and the OnDraw function in secondView class.

secondView :: secondView() : m_rectEllipse(0,0,200,200)
{
m_nColor = GRAY_BRUSH;
}

void secondView :: OnDraw (CDC* pDC)
{
pDC -> SelectStockObject (m_nColor);
pDC -> Ellipse (m_rectEllipse);
}

6. Build and run the program.

INTERFACE OBJECTS



GRAPHICS DEVICE INTERFACE OBJECTS



1. Run AppWizard to generate the third project.

2. Use ClassWizard to override the OnPrepareDC function in the thirdView class.

void thirdView :: OnPrepareDC (CDC* pDC, CPrintInfo* pInfo)

{

pDC -> SetMapMode (MM_ANISOTROPHIC);

pDC -> SetWindowExt (1440, 1440);

pDC -> SetViewPortExt (

pDC -> GetDeviceCaps (LOGPIXELSX),

pDC -> GetDeviceCaps (LOGPIXELSY));

}

3. Add a private ShowFont helper function to the view class. (thirdView.h)

private:

void ShowFont (CDC* pDC, int& nPos, int nPoints);

then add the function in thirdView.cpp

void thirdView :: ShowFont (CDC* pDC, int& nPos, int nPoints)

{

TEXTMETRIC tm;

CFont fontText;

CString strText;

CSize sizeText;

fontText.CreateFont (nPoints * 20, 0,0,0,400,FALSE,FALSE,0,

ANSI_CHARSET, OUT_DEFAULT_PRECIS,

CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_SWISS, “Arial”);

CFont* pOldFont = (CFont* ) pDC -> SelectObject (&fontText);

pDC -> GetTextMetrics (&tm);

TRACE (“points = %d, tmHeight = %d, tmExternalLeading = %d”,”tmExternalLeading = %d\n”, nPoints, tm.tmHeight, tm.tmInternalLeading, tm.tmExternalLeading);

strText.Format(“This is %d – point Arial”,nPoints);

sizeText = pDC -> GetTextExtent (strText);

TRACE(“string width = %d, string height = %d\n”, sizeText.cx, sizeText.cy);

pDC -> TextOut (0,nPos, strText);

pDC -> SelectObject (pOldFont);

nPos -= tm.tmHeight + tm.tmExternalLeading;

}

4. Edit the OnDraw function in thirdView.cpp

void thirdView :: OnDraw (CDC* pDC)

{

int nPosition = 0;

for ( int i = 6; i <= 24; i +=2)

{

ShowFont (pDC, nPosition, i);

}

TRACE (“LOGPIXEL = %d, LOGPIXEL = %d\n”,

pDC -> GetDeviceCaps (LOGPIXELSX),

pDC -> GetDeviceCaps (LOGPIXELSY));

TRACE (“HORZSIZE = %d, VERTSIZE = %d\n”,

pDC -> GetDeviceCaps (HORZSIZE),

pDC -> GetDeviceCaps (VERTSIZE));

TRACE (“HORZRES = %d, VERTRES = %d\n’,

pDC -> GetDeviceCaps ( HORZRES),

pDC -> GetDeviceCaps (VERTRES));

}

5. Build and run the program.


VIEW ARCHITECTURE

DOCUMENT – VIEW ARCHITECTURE


1. Run the AppWizard to generate a project called sixth.
2. Use the resource editor to edit the application’s main menu.
- click on the Resource View tab in the workspace window.
- edit the IDR_MAINFRAME menu resource to add a separator and a Clear Document item to the Edit menu.
- add a transfer menu and then define the following items:
Menu Caption Command ID

Edit Clear & Document ID_EDIT_CLEAR_ALL

Transfer &Get Data from Document\tF2 ID_TRANSFER_GETDATA

Transfer &Store Data from Document\tF3 ID_TRANSFER_STOREDATA
3. Use the resource editor to add keyboard accelerators.
Accelerator ID Key
ID_TRANSFER_GETDATA VK_F2
ID_TRANSFER_STOREDATA VK_F3
4. Use the ClassWizard to add the view class command and update command UI message handlers.
- add the following member functions to sixthView class:
Object ID Message Member Function
ID_TRANSFER_GETDATA COMMAND OnTransferGetData
ID_TRANSFER_STOREDATA COMMAND OnTransferStoreData
ID_TRANSFER_STOREDATA UPDATE_COMMAND_UI
OnUpdateTransferStoreData
5. Use ClassWizard to add the document class command and update command UI message handlers.
- add the following member functions to sixthDoc class.
ObjectID Message Member Function
ID_EDIT_CLEAR_ALL COMMAND OnEditClearDocument
ID_EDIT_CLEAR_ALL UPDATE_COMMAND_UI
OnUpdateEditClearDocument

6. Add a CString data member to the sixthDoc class.
- edit the sixthDoc.h file
public:
CString m_strText;
7. Edit the document class member functions in sixthDoc.cpp
BOOL sixthDoc :: OnNewDocument()
{
if (!CDocument :: OnNewDocument())
return FALSE;
m_strText = “Hello (from sixthDoc :: OnNewDocument)”;
return TRUE;
}

void sixthDoc :: OnEditClearDocument()
{
m_strText.Empty();
}


void sixthDoc :: OnUpdateEditClearDocument(CCmdUI* pCmdUI)
{
pCmdUI -> Enable (!m_strText.IsEmpty());
}

8. Add a CRichEditCtrl data member to the sixthView class.
- edit the sixthView.h class
public:
CRichEditCtrl m_rich;
9. Use the ClassWizard to map the WM_CREATE and WM_SIZE messages in the sixthView class.

int sixthView :: OnCreate (LPCREATESTRUCT lpCreateStruct)
{
CRect rect (0,0,0,0);
if (CView :: OnCreate (lpCreateStruct) == -1)
return -1;
m_rich.Create (ES_AUTOVSCROLL | ES_MULTILINE |
ES_WANTRETURN | WS_CHILD | WS_VISIBLE |
WS_VSCROLL ,rect,this,1);
return 0;
}

void sixthView :: OnSize (UINT nType, int cx, int cy)
{
CRect rect;
CView OnSize (nType, cx, cy);
GetClientRect (rect);
m_rich.SetWindowPos (&wndTop, 0, 0, rect.right – rect.left,
rect.bottom – rect.top, SWP_SHOWWINDOW);
}
10. Edit the menu command handler functions in sixthView.cpp

void sixthView :: OnTransferGetData()
{
sixthDoc* pDoc = GetDocument();
m_rich.SetWindowText (pDoc -> m_strText);
m_rich.SetModify (FALSE);
}

void sixthView :: OnTransferStoreData()
{
sixthDoc* pDoc = GetDocument();
m_rich.GetWindowText (pDoc -> m_strText);
m_rich.SetModify (FALSE);
}

void sixthView :: OnUpdateTransferStroeData (CCmdUI* pCmdUI)
{
pCmdUI -> Enable (m_rich.GetModify());
}

11. Build and Test the sixth application.

TOOL BARS



TOOL BARS


  1. Run AppWizard to generate toolbar application.
  2. Use the resource editor to edit the application’s main menu.

- In resource view, double – click on IDR_MAINFRAME.

- create a new menu called draw with the following names & command ID’s

Menu Caption Command ID

Draw Circle ID_DRAW_CIRCLE

Draw Square ID_DRAW_SQUARE

Draw Pattern ID_DRAW_PATTERN

3. Use ClassWizard to add toolbarView class message handlers.

Object ID Message Member Function

ID_DRAW_CIRCLE COMMAND OnDrawCircle

ID_DRAW_CIRCLE UPDATE_COMMAND_UI OnUpdateDrawCircle

ID_DRAW_PATTERN COMMAND OnDrawPattern

ID_DRAW_PATTERN UPDATE_COMMAND_UI OnUpdateDrawPattern

ID_DRAW_SQUARE COMMAND OnDrawSquare

ID_DRAW_SQUARE UPDATE_COMMAND_UI OnUpdateDrawSquare

4. Add three data members to the toolbarView class.

- edit the file toolbarView.h

private:

CRect m_rect;

BOOL m_bCircle;

BOOL m_bPattern;

5. Edit the toolbarView.cpp file

CtoolbarView :: CtoolbarView() : m_rect (0,0,100,100)

{

m_bCircle = TRUE;

m_bPattern = FALSE;

}

Edit the OnDraw function.

void CtoolbarView :: OnDraw (CDC* pDC)

{

CBrush brush(HS_BDIAGONAL, 0L);

if (m_bPattern)

pDC -> SelectObject (&brush);

else

pDC -> SelectStockObject (WHITE_BRUSH);

if (m_bCircle)

pDC -> Ellipse (m_rect);

else

pDC -> Rectangle (m_rect);

pDC -> SelectStockObject (WHITE_BRUSH);

}

Edit the OnDrawCircle, OnDrawSquare and OnDrawPattern function.

void CtoolbarView :: OnDrawCircle()

{

m_bCircle = TRUE;

m_rect += CPoint (25,25);

InvalidateRect (m_rect);

}

void CtoolbarView :: OnDrawSquare()

{

m_bCircle = FALSE;

m_rect += CPoint (25,25);

InvalidateRect (m_rect);

}

void CtoolbarView :: OnDrawPattern()

{

m_bPattern ^= 1;

}

Edit the OnUpdateDrawCircle, OnUpdateDrawSquare and OnUpdateDrawPattern function

void CtoolbarView :: OnUpdateDrawCircle (CCmdUI* pCmdUI)

{

pCmdUI -> Enable (!m-bCircle);

}

void CtoolbarView :: OnUpdateDrawSquare (CCmdUI* pCmdUI)

{

pCmdUI -> Enable (m_bCircle);

}

void CtoolbarView :: OnUpdateDrawPattern (CCmdUI* pCmdUI)

{

pCmdUI -> SetCheck (m_bPattern);

}

8. Build and Test the application.


STATUS BARS

STATUS BARS




1. Run AppWizard to generate statusbar application.

1. Use the string editor to edit the application’s string table resource.
- double click on the string table icon in the string table folder on the ResourceView page to bring up the string editor.
- then double click on the empty entry at the end of the list.
- assign the ID and string value in the dialog as:

String ID String Caption
ID_INDICATOR_LEFT LEFT
ID_INDICATOR_RIGHT RIGHT
3. Use Visual C++ to edit the application’s symbols.
- choose Resource symbols from the View menu.
- add the new status bar identifier, ID_MY_STATUS_BAR and accept the default value.

4. Use ClassWizard to add View menu command handlers in the class CMainFrame.
- add the following message handlers

Object ID Message Member Function
ID_VIEW_STATUS_BAR COMMAND OnViewStatusBar
ID_VIEW_STATUS_BAR UPDATECOMMAND_UI
OnUpdateViewStatusBar
5. Add the function prototypes to MainFrm.h file

afx_msg void OnUpdateLeft (CCmdUI* pCmdUI);
afx_msg void OnUpdateRight (CCmdUI* pCmdUI);

add the message handler statements inside the AFX_MSG brackets so that ClassWizard will access and edit the code later.

6. Edit the MainFrm.cpp file
- replace the original indicators array with the following code
static UINT indicators[] =
{
ID_SEPARATOR,
ID_SEPARATOR,
ID_INDICATOR_LEFT,
ID_INDICATOR_RIGHT< }; - edit the OnCreate member function if (!m_wndStatusBar.Create (this, WS_CHILD | WS_VISIBLE | CBRS_BOTTOM | ID_MY_STATUS_BAR) || !m_wndStatusBar.SetIndicators (indicators, sizeof (indicators) / sizeof(UINT))); { TRACE0(“Failed to create status bar\n”); return -1; } Add the following message map entries for the class CMainFrame. ON_UPDATE_COMMAND_UI (ID_INDICATOR_LEFT, OnUpdateLeft) ON_UPDATE_COMMAND_UI (ID_INDICATOR_RIGHT, OnUpdateRight) Add the following CMainFrame member function that updates the two status indicators. void CMainFrame :: OnUpdateLeft (CCmdUI* pCmdUI) { pCmdUI -> Enable (::GetKeyState (VK_LBUTTON) <> Enable (::GetKeyState (VK_RBUTTON) <0);> SetCheck(m_wndStatusBar.GetStyle() &
WS_VISIBLE) != 0);
}
8. Edit the OnDraw function in statusView.cpp
void CstatusView :: OnDraw (CDC* pDC)
{
pDC -> TextOut (0,0, “Watch the status bar”);
}
9. Add a WM_MOUSEMOVE handler in the CstatusView class
void CstatusView :: OnMouseMove (UINT nFlags, CPoint point)
{
CString str;
CMainFrame* pFrame = (CMainFrame*) AfxGetApp() ->m_pMainWnd;
CStatusBar* pStatus = &pFrame -> m_wndStatusBar;
if (pStatus){
str.Format (“X =%d”, point.x);
pStatus -> SetPaneText (0, str);
str.Format (“Y=%d”, point.y);
pStatus -> SetPaneText(1,str);
}
}

Finally add the statement

#include “MainFrm.h”

near the top of the file statusView.cpp

9. Build and test the application.

INTERFACE WITH DATABASE



INTERFACE WITH DATABASE

1. Create a database named stud in MS Access.

2. Run the ODBC Data Source administrator to install the stud data source.

- click on the ODBC icon in the windows control panel.

- click the Add button and choose Microsoft Access Driver in the Add Data Source dialog box.

- select the database by clicking the Select button and then press OK.

3. Run AppWizard to create student application.