SlideShare a Scribd company logo
Department of Computer Applications
Lab Manual
MC1755 – Visual Programming
(IV Semester)
Prepared by:
Ms. V.Kayathri
Ms. N.M. Kavitha & Ms.G.Padmavathy
(Lect. / MCA) (Lect. / MCA)
RAJALAKSHMI ENGINEERING COLLEGE
Rajalakshmi Nagar, Thandalam, Chennai – 602 105
1
List of Lab Exercises
Sl.
No.
Exercise Page No.
1. Window Creation
2. Message Map Functions
3. Graphical Device Interface
4. Single Document Interface
5. Multiple Document Interface
6. Toolbar Creation
7. Status bar Creation
8. Menu bar Creation
9. Modal Dialog Box Creation
10. Modeless Dialog Box Creation
11. Model Dialog Box creation – Student Details
12. Dynamic Controls
13. SDI Serialization
14. MDI serialization
15. ODBC connectivity
16. Dynamic Link Library
17. Document View Architecture
2
Ex.No: 1
Window Creation
Date :
Aim:
To write a Visual C++ program for creating a window using win32 application.
Logical Description:
The program starts with object creation. After initializing the instance, the user
created window is assigned as main window. Using Show window option project user
created window.
Algorithm:
1. Start the Process
2. Create an object for an class which inherits CWinApp
3. The object access InitInstance() function
4. Create a pointer object for the class which inherits CFrameWindow by allocating
the memory to the object
5. Show the created window using SW_SHOWNORMAL
6. Stop the process
Source Code:
#include<afxwin.h>
class mywnd : public CFrameWnd
{
public:
mywnd()
{
Create(0, "My window");
}
};
class myapp: public CWinApp
{
public :
BOOL InitInstance()
{
mywnd *p;
p = new mywnd;
m_pMainWnd = p ; // main thread
3
p->ShowWindow(SW_SHOWNORMAL);
return TRUE;
}
};
myapp A;
Output:
4
Ex.No: 2
Message Map Functions
Date :
Aim:
To write a Visual C++ program which uses message map functions using win32
application.
Logical Description:
The program starts with object creation. After initializing the instance, the user
created window is assigned as main window. Using Show window option project user
created window. Using message map option draw circles when ever mouse moves on the
client area.
Algorithm:
1. Start the Process
2. Create an object for a myapp class. Invoke InitInstance function and create object
for mywin to call the constructor mywin.
3. A window is created by calling the create function which resides inside the
constructor
4. Inside message map write the code for draw circle inside the view window.
5. Show the created window using SW_SHOWNORMAL
6. Stop the process
Source Code:
#include<afxwin.h>
class mywin :public CFrameWnd
{
public:
mywin()
{
Create(0,"MFC");
}
DECLARE_MESSAGE_MAP()
void OnMouseMove(UINT f,CPoint p)
{
CClientDC dc(this);
5
dc.Ellipse(p.x,p.y,p.x+50,p.y+50);
}
};
BEGIN_MESSAGE_MAP(mywin,CFrameWnd)
ON_WM_MOUSEMOVE()
END_MESSAGE_MAP()
class myapp : public CWinApp
{
public:
BOOL InitInstance()
{
mywin *p;
p = new mywin();
m_pMainWnd = p;
p->ShowWindow(SW_SHOWNORMAL);
return TRUE;
}
};
myapp A;
Output:
6
Ex.No: 3
Graphical Device Interface
Date :
Aim:
To write a Visual C++ program which uses the GDI tools
Logical Description:
The program starts with object creation. After initializing the instance, the user
created window is assigned as main window. Using Show window option project user
created window. Using message map create a pen & brush. Using that pen & brush draw
objects.
Algorithm:
1. Start the Process
2. Create an object for an myapp class. Invoke InitInstance function and create
object for mywin to call the constructor mywin.
3. A window is created by calling the create function which resides inside the
constructor
4. Inside message map write the code for GDI objects like pen & brush .
5. Show the created window using SW_SHOWNORMAL
6. Stop the process
Source Code:
#include <afxwin.h>
class mywnd : public CFrameWnd
{
public:
mywnd()
{
Create(0,"MFC");
}
DECLARE_MESSAGE_MAP()
void OnLButtonDown(UINT f,CPoint p)
{
CPen pen;
CBrush brush;
7
CClientDC dc(this);
pen.CreatePen(PS_SOLID, 5,RGB(200,120,130));
brush.CreateHatchBrush(HS_VERTICAL,RGB(50,50,130));
dc.SelectObject(pen);
dc.SelectObject(brush);
dc.Rectangle(200,200,300,300);
}
void OnRButtonDown(UINT f,CPoint p)
{
CPen pen;
CBrush brush;
CClientDC dc(this);
pen.CreatePen(PS_SOLID, 5,RGB(123,134,130));
brush.CreateHatchBrush(HS_HORIZONTAL,RGB(150,150,230));
dc.SelectObject(pen);
dc.SelectObject(brush);
dc.Rectangle(50,50,200,200);
}
};
BEGIN_MESSAGE_MAP(mywnd,CFrameWnd)
ON_WM_LBUTTONDOWN()
ON_WM_RBUTTONDOWN()
END_MESSAGE_MAP()
class myapp : public CWinApp
{
public:
BOOL InitInstance()
{
mywnd *p;
p = new mywnd();
m_pMainWnd = p;
p->ShowWindow(SW_SHOWNORMAL);
return true;
}
};
myapp A;
8
Output:
9
Ex.No: 4
Single Document Interface
Date :
Aim:
To create a SDI (Application Wizard) and to draw an ellipse inside the view
window using Device Context.
Logical Description:
Using wizards create a single document interface
Algorithm:
1. File – New – Projects tab – MFC Appwizard (exe) – Give the location
name and the project name – ok
2. Select single Document option.
3. Accept the defaults in the next four screens.
4. Click the finish button – ok button.
[ProgramnameView.cpp and ProgramnameView.h files define the
CprogramnameView class, which is central to the application ]
5. In the .cpp file , write the following code in the OnDraw function
void CprogramnameView :: OnDraw(CDC *pDC)
PDC  TextOut(0,0, “Hello World “);
PDC  SelectStockObject(GRAY_BRUSH);
PDC  Ellipse(CRect(0,20,100,120));
These 3 are the member functions of the application framework’s device context
class CDC.
6. Build and execute the Application.
Source Code:
// sdiView.cpp : implementation of the CSdiView class
//
#include "stdafx.h"
#include "sdi.h"
10
#include "sdiDoc.h"
#include "sdiView.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CSdiView
IMPLEMENT_DYNCREATE(CSdiView, CView)
BEGIN_MESSAGE_MAP(CSdiView, CView)
//{{AFX_MSG_MAP(CSdiView)
// NOTE - the ClassWizard will add and remove mapping macros here.
// DO NOT EDIT what you see in these blocks of generated code!
//}}AFX_MSG_MAP
// Standard printing commands
ON_COMMAND(ID_FILE_PRINT, CView::OnFilePrint)
ON_COMMAND(ID_FILE_PRINT_DIRECT, CView::OnFilePrint)
ON_COMMAND(ID_FILE_PRINT_PREVIEW, CView::OnFilePrintPreview)
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CSdiView construction/destruction
CSdiView::CSdiView()
{
// TODO: add construction code here
}
CSdiView::~CSdiView()
{
}
BOOL CSdiView::PreCreateWindow(CREATESTRUCT& cs)
{
// TODO: Modify the Window class or styles here by modifying
// the CREATESTRUCT cs
return CView::PreCreateWindow(cs);
}
11
/////////////////////////////////////////////////////////////////////////////
// CSdiView drawing
void CSdiView::OnDraw(CDC* pDC)
{
CSdiDoc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
pDC->TextOut(0,0,"Hello world");
pDC->SelectStockObject(GRAY_BRUSH);
pDC->Ellipse(CRect(0,20,100,120));
}
/////////////////////////////////////////////////////////////////////////////
// CSdiView printing
BOOL CSdiView::OnPreparePrinting(CPrintInfo* pInfo)
{
// default preparation
return DoPreparePrinting(pInfo);
}
void CSdiView::OnBeginPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/)
{
// TODO: add extra initialization before printing
}
void CSdiView::OnEndPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/)
{
// TODO: add cleanup after printing
}
/////////////////////////////////////////////////////////////////////////////
// CSdiView diagnostics
#ifdef _DEBUG
void CSdiView::AssertValid() const
{
CView::AssertValid();
}
void CSdiView::Dump(CDumpContext& dc) const
{
CView::Dump(dc);
}
12
CSdiDoc* CSdiView::GetDocument() // non-debug version is inline
{
ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CSdiDoc)));
return (CSdiDoc*)m_pDocument;
}
#endif //_DEBUG
/////////////////////////////////////////////////////////////////////////////
// CSdiView message handlers
Output:
13
Ex.No: 5
Multiple Document Interface
Date :
Aim:
To create a MDI (Application Wizard) and to draw an ellipse inside the view
window using Device Context.
Logical Description:
Using wizards create a multiple document interface
Algorithm:
1. File – New – Projects tab – MFC Appwizard (exe) – Give the location name and
the project name – ok
2. Select Multiple Document option.
3. Accept the defaults in the next four screens.
4. Click the finish button – ok button.
[ProgramnameView.cpp and ProgramnameView.h files define the
CprogramnameView class, which is central to the application ]
5. In the .cpp file , write the following code in the OnDraw function
void CprogramnameView :: OnDraw(CDC *pDC)
PDC  TextOut(0,0, “Hello World “);
PDC  SelectStockObject(GRAY_BRUSH);
PDC  Ellipse(CRect(0,20,100,120));
These 3 are the member functions of the application framework’s device context
class CDC.
6. Build and execute the Application.
Source Code:
// mdiView.cpp : implementation of the CMdiView class
#include "stdafx.h"
#include "mdi.h"
#include "mdiDoc.h"
14
#include "mdiView.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CMdiView
IMPLEMENT_DYNCREATE(CMdiView, CView)
BEGIN_MESSAGE_MAP(CMdiView, CView)
//{{AFX_MSG_MAP(CMdiView)
// NOTE - the ClassWizard will add and remove mapping macros here.
// DO NOT EDIT what you see in these blocks of generated code!
//}}AFX_MSG_MAP
// Standard printing commands
ON_COMMAND(ID_FILE_PRINT, CView::OnFilePrint)
ON_COMMAND(ID_FILE_PRINT_DIRECT, CView::OnFilePrint)
ON_COMMAND(ID_FILE_PRINT_PREVIEW, CView::OnFilePrintPreview)
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CMdiView construction/destruction
CMdiView::CMdiView()
{
// TODO: add construction code here
}
CMdiView::~CMdiView()
{
}
BOOL CMdiView::PreCreateWindow(CREATESTRUCT& cs)
{
// TODO: Modify the Window class or styles here by modifying
// the CREATESTRUCT cs
return CView::PreCreateWindow(cs);
}
/////////////////////////////////////////////////////////////////////////////
// CMdiView drawing
15
void CMdiView::OnDraw(CDC* pDC)
{
CMdiDoc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
pDC->TextOut(0,0, "Hello World ");
pDC->SelectStockObject(GRAY_BRUSH);
pDC->Ellipse(CRect(0,20,100,120));
}
/////////////////////////////////////////////////////////////////////////////
// CMdiView printing
BOOL CMdiView::OnPreparePrinting(CPrintInfo* pInfo)
{
// default preparation
return DoPreparePrinting(pInfo);
}
void CMdiView::OnBeginPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/)
{
// TODO: add extra initialization before printing
}
void CMdiView::OnEndPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/)
{
// TODO: add cleanup after printing
}
/////////////////////////////////////////////////////////////////////////////
// CMdiView diagnostics
#ifdef _DEBUG
void CMdiView::AssertValid() const
{
CView::AssertValid();
}
void CMdiView::Dump(CDumpContext& dc) const
{
CView::Dump(dc);
}
CMdiDoc* CMdiView::GetDocument() // non-debug version is inline
{
16
ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CMdiDoc)));
return (CMdiDoc*)m_pDocument;
}
#endif //_DEBUG
/////////////////////////////////////////////////////////////////////////////
// CMdiView message handlers
Output:
17
Ex.No: 6
Tool bar Creation
Date :
Aim:
To write a VC++ program to create a toolbar which displays different shapes
when the buttons are clicked from tool bar.
Logical Description:
The program starts with object creation. After initializing the instance, the user
created window is assigned as main window. Using Show window option project user
created window. Using resources option create a toolbar & attach it to the user created
window.
Algorithm:
1. Start the process
2. Create 4 buttons for displaying circle, rectangle, square and exit by inserting
resources and saving them with their respective names.
3. Create 4 functions to its corresponding IDs draw
4. Map these 4 functions to its corresponding IDs.
5. Create a tool bar tab from its base class CToolBar in a function names
OnCreate().
6. Allocate memory space for toolbar
7. Load the tool bar and create it using the functions load toolbar and enable
docking.
8. Set the style of the toolbar by using SetBarStyle functions
9. Stop the process
Source Code:
#include<afxwin.h>
#include<afxext.h>
#include "resource.h"
class mywin:public CFrameWnd
{
public:
18
mywin()
{
Create(0,"TOOLBAR");
}
DECLARE_MESSAGE_MAP()
void OnExit()
{
PostQuitMessage(0);
}
void OnCir()
{
CClientDC dc(this);
dc.Ellipse(50,50,100,100);
}
void OnRect()
{
CClientDC dc(this);
CPen pen;
CBrush brush;
dc.Rectangle(220,220,300,250);
pen.CreatePen(PS_SOLID,3,RGB(250,0,0));
brush.CreateSolidBrush(RGB(340,240,75));
dc.SelectObject(pen);
dc.SelectObject(brush);
}
void OnSqu()
{
CClientDC dc(this);
dc.Rectangle(150,150,200,200);
}
int OnCreate(LPCREATESTRUCT lp)
{
CToolBar *tb;
tb=new CToolBar();
tb->Create(this);
tb->LoadToolBar(MAKEINTRESOURCE(IDR_TOOLBAR1));
EnableDocking(CBRS_ALIGN_ANY);
tb->EnableDocking(CBRS_ALIGN_ANY);
tb->SetBarStyle(tb->GetBarStyle()|CBRS_TOOLTIPS);
DockControlBar(tb);
return true;
}
};
BEGIN_MESSAGE_MAP(mywin,CFrameWnd)
ON_COMMAND(ID_CIRCLE,OnCir)
ON_COMMAND(ID_RECTANGLE,OnRect)
19
ON_COMMAND(ID_SOUARE,OnSqu)
ON_COMMAND(ID_EXIT,OnExit)
ON_WM_CREATE()
END_MESSAGE_MAP()
class myapp:public CWinApp
{
public:
BOOL InitInstance()
{
mywin *p;
p=new mywin();
m_pMainWnd=p;
p->ShowWindow(SW_SHOWNORMAL);
return true;
}
};
myapp A;
Output:
20
Ex.No: 7
Status bar Creation
Date :
Aim:
To write a VC++ program to create a window which contains status bar
Logical Description:
The program starts with object creation. After initializing the instance, the user
created window is assigned as main window. Using Show window option project user
created window. Using resources option create a statusbar & attach it to the user created
window.
Algorithm:
1. Start the process
2. Initially control starts from object creation
3. Then it calls the myapp class which has the main function is which constructor is
invoked using the pointer variable.
4. Constructor mywin then creates the window
5. After the DECLARE_MESSAGE_MAP macro, specify the codeing for message
handlers. OnMyRect(), OnMysquare(), OnMyCircle() and OnMyExit().
6. In the OnCreate message handler, specify the status bar base class, create an
instance of it and use the instance of it and use the instance to create the status bar
7. Next define the messages corresponding to the message handlers defines above
then assign the user created window as the main window and project the same
using show window
8. Finally when the user moves the mouse on the options corresponding message
appears on status bar and on selection of the option, the corresponding figure is
displayed
9. Stop the process
21
Source Code:
#include<afxwin.h>
#include<afxext.h>
#include"resource.h"
class mywin : public CFrameWnd
{
public :
mywin()
{
Create(0,"MFC",WS_OVERLAPPEDWINDOW,
CRect(100,100,600,500),0,
MAKEINTRESOURCE(IDR_MENU1));
}
DECLARE_MESSAGE_MAP()
int OnCreate(LPCREATESTRUCT lp)
{
UINT panes[] = {0,0,ID_INDICATOR_CAPS,
ID_INDICATOR_NUM,ID_INDICATOR_SCRL};
CStatusBar *sb;
sb = new CStatusBar();
sb->Create(this);
sb->SetIndicators(panes,5);
return 0;
}
void OnMyExit()
{
PostQuitMessage(0);
}
};
BEGIN_MESSAGE_MAP(mywin,CFrameWnd)
ON_COMMAND(ID_EXIT,OnMyExit)
ON_WM_CREATE()
END_MESSAGE_MAP()
class myapp : public CWinApp
{
public:
BOOL InitInstance()
{
mywin *p;
p = new mywin();
22
m_pMainWnd = p;
p->ShowWindow(SW_SHOWNORMAL);
return TRUE;
}
};myapp A;
Output:
23
Ex.No: 8
Menu bar creation
Date :
Aim:
To write a VC++ program to create a menu bar which displays when the menu
items are selected from the menu bar
Logical Description:
The program starts with object creation. After initializing the instance, the user
created window is assigned as main window. Using Show window option project user
created window. Using resources option create a menu bar & attach it to the user created
window.
Algorithm:
1. Start the process
2. Create a tool bar tab from its base class CToolbar in a function name OnCreate().
3. Create 4 buttons for displaying circle, rectangle, square and exit by inserting
resources and saving them with their respective names
4. Create 4 functions to its corresponding IDs draw
5. Map these 4 functions to its corresponding IDs
6. Allocate memory space for tool bar
7. Load the tool bar and create it using the functions load tool bar and enable
docking
8. Set the style of the tool bar by using SetBarStyle function
9. After the DECLARE_MESSAGE_MAP macro, specify the coding for message
handlers. OnRect(), OnSquare(), OnCircle() and OnExit()
10. Load the tool bar
11. Stop the process
24
Source Code:
#include<afxwin.h>
#include"resource.h"
class myframe:public CFrameWnd
{
public:
int u,u1,u2,u3;
COLORREF b;
myframe()
{
Create(0,"DRAWINGS",WS_OVERLAPPED |
WS_SYSMENU,CRect(0,0,500,500),0,MAKEINTRESOURCE(IDR_MENU1));
}
void OnPaint();
void Rectangle()
{
u =1;
Invalidate();
}
void Circle()
{
u =2;
Invalidate();
}
void Ellipse()
{
u =3;
Invalidate();
}
void Square()
{
u =4;
Invalidate();
}
void Line()
{
u =5;
Invalidate();
}
void Solid()
{
u2 =1;
Invalidate();
}
void Dash()
25
{
u2 =2;
Invalidate();
}
void Dashdot()
{
u2 = 3;
Invalidate();
}
void Cross()
{
u3 = 1;
Invalidate();
}
void Diagonal()
{
u3 =2;
Invalidate();
}
void Fdiagonal()
{
u3 =3;
Invalidate();
}
void Red()
{
u1 =1;
Invalidate();
}
void Green()
{
u1 =2;
Invalidate();
}
void Blue()
{
u1 =3;
Invalidate();
}
DECLARE_MESSAGE_MAP()
};
BEGIN_MESSAGE_MAP(myframe,CFrameWnd)
ON_COMMAND(ID_RECT,Rectangle)
ON_COMMAND(ID_CIR,Circle)
ON_COMMAND(ID_ELL,Ellipse)
ON_COMMAND(ID_SQR,Square)
26
ON_COMMAND(ID_LIN,Line)
ON_COMMAND(ID_R,Red)
ON_COMMAND(ID_G,Green)
ON_COMMAND(ID_B,Blue)
ON_COMMAND(121,Solid)
ON_COMMAND(122,Dash)
ON_COMMAND(123,Dashdot)
ON_COMMAND(131,Cross)
ON_COMMAND(132,Diagonal)
ON_COMMAND(133,Fdiagonal)
ON_WM_PAINT()
END_MESSAGE_MAP()
void myframe::OnPaint()
{
int bst = 0;
switch(u3)
{
case 1:
bst = HS_CROSS;
break;
case 2:
bst = HS_BDIAGONAL;
break;
case 3:
bst = HS_FDIAGONAL;
break;
}
switch(u1)
{
case 1:
b = RGB(255,0,0);
break;
case 2:
b = RGB(0,255,0);
break;
case 3:
b = RGB(0,0,255);
break;
}
int pst = 0;
switch(u2)
{
case 1:
27
pst = PS_SOLID;
break;
case 2:
pst = PS_DASH;
break;
case 3:
pst = PS_DASHDOT;
break;
}
CPaintDC dc(this);
CPen p;
p.CreatePen(pst,1,RGB(0,0,0));
CBrush br(bst,b);
dc.SelectObject(&br);
dc.SelectObject(&p);
switch(u)
{
case 1:
dc.Rectangle(70,100,400,300);
break;
case 2:
dc.Ellipse(300,300,150,150);
break;
case 3:
dc.Ellipse(300,300,200,100);
break;
case 4:
dc.Rectangle(100,100,200,200);
break;
case 5:
dc.MoveTo(200,200);
dc.LineTo(400,400);
break;
}
}
class myapp:public CWinApp
{
public:
BOOL InitInstance()
{
myframe *p;
p = new myframe();
m_pMainWnd = p;
p->ShowWindow(SW_SHOWNORMAL);
return TRUE;
}
28
};
myapp A;
Output:
29
Ex.No: 9
Modal Dialog box Creation
Date :
Aim:
To write a VC++ program for creating a modal dialog box
Logical Description:
The program starts with object creation. After initializing the instance, the user
created window is assigned as main window. Using Show window option project user
created window. Using resources option create a Modal dialog box & attach it to the user
created window.
Algorithm:
1. Start the process
2. Initially control starts from object creation
3. Create a dialog box of type modal
4. using IDD_DIALOG1 crate a new dialog box and add the items in it
5. Type cast te allocated memory obtained using GetDlgItem() function into CListBox
and assign it to lb which is of type CListBox
6. Add the data given in the edit box IDC_EDIT1 into the listbox IDC_LIST1 using a
user created add function
7. Remove the data given in the list box IDC_LIST1 by clicking remove button
which is actually a user defined function
8. Stop the process
Source Code:
#include<afxwin.h>
#include<afxdlgs.h>
#include "resource.h"
class mydlg:public CDialog
{
private:
CListBox *lb;
public:
30
mydlg():CDialog(IDD_DIALOG1)
{
}
public:
BOOL OnInitDialog()
{
SetDlgItemText(IDC_EDIT1,"Welcome");
lb=(CListBox*)GetDlgItem(IDC_LIST1);
lb->AddString("Chennai");
lb->AddString("Erode");
lb->AddString("Trichy");
lb->AddString("Coimbatore");
return TRUE;
}
void OnOK()
{
EndDialog(TRUE);
}
void OnCancel()
{
EndDialog(FALSE);
}
void OnMyAdd()
{
char st[100];
GetDlgItemText(IDC_EDIT1, st,100);
lb->AddString(st);
}
void OnMyDel()
{
int s;
s = lb->GetCurSel();
if (s>= 0)
lb->DeleteString(s);
}
DECLARE_MESSAGE_MAP()
};
BEGIN_MESSAGE_MAP(mydlg,CDialog)
ON_COMMAND(IDC_ADD,OnMyAdd)
ON_COMMAND(IDC_DEL,OnMyDel)
END_MESSAGE_MAP()
31
class mywin:public CFrameWnd
{
public:
mywin()
{
Create(0,"MFC WINDOW");
}
void OnRButtonDown(UINT f,CPoint p)
{
mydlg dlg;
dlg.DoModal();
}
DECLARE_MESSAGE_MAP()
};
BEGIN_MESSAGE_MAP(mywin,CFrameWnd)
ON_WM_RBUTTONDOWN()
END_MESSAGE_MAP()
class myapp:public CWinApp
{
public:
BOOL InitInstance()
{
mywin *p;
p=new mywin();
m_pMainWnd=p;
p->ShowWindow(SW_SHOWNORMAL);
return true;
}
};
myapp A;
32
Output:
33
Ex.No: 10
Modeless Dialog box Creation
Date :
Aim:
To write a VC++ program to display the text on modeless dialog box
Logical Description:
The program starts with object creation. After initializing the instance, the user
created window is assigned as main window. Using Show window option project user
created window. Using resources option create a Modeless dialog box & attach it to the
user created window.
Algorithm:
1. Start the process
2. Create a dialog box using IDD_DIALOG1 and add the items in it
3. The creation of the dialog box can be done with the help of CDialog creating
an instance to it.
4. Allocate memory to the created instance
5. Call the create method (creation of instance) on the event RButtonDown
6. Stop the process
Source Code:
#include<afxwin.h>
#include<afxdlgs.h>
#include "resource.h"
class mydlg:public CDialog
{
public:
mydlg():CDialog()
{
}
public:
BOOL OnInitDialog()
34
{
return TRUE;
}
void OnOK()
{
EndDialog(TRUE);
}
void OnCancel()
{
EndDialog(FALSE);
}
DECLARE_MESSAGE_MAP()
};
BEGIN_MESSAGE_MAP(mydlg,CDialog)
ON_COMMAND(IDC_CIRCLE, OnCircle)
ON_COMMAND(IDC_SQUARE, OnSquare)
END_MESSAGE_MAP()
class mywin:public CFrameWnd
{
public:
mywin()
{
Create(0,"MFC WINDOW");
}
void OnRButtonDown( )
{
CDialog *dlg;
dlg = new mydlg();
dlg->Create(IDD_DIALOG1);
dlg->ShowWindow(1);
}
DECLARE_MESSAGE_MAP()
};
BEGIN_MESSAGE_MAP(mywin,CFrameWnd)
ON_WM_RBUTTONDOWN()
END_MESSAGE_MAP()
class myapp:public CWinApp
{
35
public:
BOOL InitInstance()
{
mywin *p;
p=new mywin();
m_pMainWnd=p;
p->ShowWindow(SW_SHOWNORMAL);
return true;
}
}; myapp A;
Output:
36
Ex.No: 11
Modal Dialog box Creation – Student Details
Date :
Aim:
To write a VC++ program to display the text on modeless dialog box
Logical Description:
The program starts with object creation. After initializing the instance, the user
created window is assigned as main window. Using Show window option project user
created window. Using resources option create a Modeless dialog box & attach it to the
user created window.
Algorithm:
1. Start the process
2. Create a dialog box using IDD_DIALOG1 and add the items in it
3. The creation of the dialog box can be done with the help of CDialog creating
an instance to it.
4. Allocate memory to the created instance
5. Call the create method (creation of instance) on the event RButtonDown
6. Stop the process
Source Code:
#include<afxwin.h>
#include<afxdlgs.h>
#include”resource.h”
class mydialog::public CDialog
{
public:
mydialog():CDialog(IDD_DIALOG1)
{ }
BOOL OnInitDialog()
{
SetDlgItemText(IDC_EDIT1, “”);
SetDlgItemText(IDC_EDIT2, “”);
CheckRadioButton(IDC_RADIO1,IDC_RADIO2,IDC_RADIO3);
CheckDlgButton(IDC_CHECK1,0);
37
CheckDlgButton(IDC_CHECK2,0);
CheckDlgButton(IDC_CHECK3,0);
CheckDlgButton(IDC_CHECK4,0);
return true;
}
void OnOK()
{
CString name, result;
result+=”Name”;
GetDlgItemText(IDC_EDIT1,name);
result+=name;
result+=”n”;
result+=”AGE”;
CString st;
GetDlgItemText(IDC_EDIT2,st);
result+=st;
result+=”n”;
result+=”YEAR”;
int college=GetCheckedRadioButton(IDC_RADIO1, IDC_RADIO3);
switch(college)
{
case IDC_RADIO1:
result+=”I Year”;
break;
case IDC_RADIO2:
result+=”II Year”;
break;
case IDC_RADIO3:
result+=”III Year”;
break;
}
result+=”n”;
result+=”PASSED IN: ”;
if(IsDlgButtonChecked(IDC_CHECK1)==1)
result+=”Unix”;
if(IsDlgButtonChecked(IDC_CHECK2)==1)
result+=”VC++”;
if(IsDlgButtonChecked(IDC_CHECK3)==1)
result+=”OOAD”;
if(IsDlgButtonChecked(IDC_CHECK4)==1)
result+=”RMT”;
MessageBox(result, “RESULT”);
}
void OnCancel()
{
CDialog::OnCancel();
38
MessageBox(“Cancelled”);
}
};
class mywin::public CFrameWnd
{
public:
mywin()
{
Create(0,”MFC”,WS_OVERLAPPEDWINDOW, CRect(100,100,600,500),0,
MAKEINTRESOURCE(IDR_MENU1);
}
void result()
{
mydialog d;
d.DoModal();
}
void end()
{
PostQuitMessage(0);
}
DECLARE_MESSAGE_MAP()
};
BEGIN_MESSAGE_MAP(mywin, CFrameWnd)
ON_COMMAND(101, result);
ON_COMMAND(102,end);
END_MESSAGE_MAP()
Class myapp:public CWinApp
{
BOOL InitInstance()
{
mywin *p;
p= new mywin();
m_pMainWnd=p;
p->ShowWindow(1);
return true;
}
};
myapp A;
39
Output:
40
Ex.No: 12
Dynamic Controls
Date :
Aim:
To write a VC++ program to implement the dynamic controls
Logical Description:
The program starts with object creation. After initializing the instance, the user
created window is assigned as main window. Using Show window option project user
created window. Using message mapping create dynamically controls such as label, edit
box and button
Algorithm:
1. Start the process
2. Initially control starts from object creation
3. Next it calls the myapp class which in turn calls the constructor
4. The constructor creates an Output:window
5. Create name, address, phone and password using WS_VISIBLE, WS_CHILD
& SS_CENTREIMAGE.
6. Define respective message maps for the corresponding functions.
7. Execute the program
8. Stop the process
Source Code:
#include<afxwin.h>
#include<ctype.h>
#define EDIT_NUM 100
#define BUT_OK 103
class myedit:public CEdit
{
public:
void OnChar(UINT nChar,UINT nRepCnt,UINT nFlags)
{
if(isdigit(nChar))
CEdit::OnChar(nChar,nRepCnt,nFlags);
else
::MessageBeep(0);
41
}
DECLARE_MESSAGE_MAP()
};
BEGIN_MESSAGE_MAP(myedit,CEdit)
ON_WM_CHAR()
END_MESSAGE_MAP()
class mywin:public CFrameWnd
{
private:
myedit edit_num;
CStatic label;
CButton okbut;
public:
mywin()
{
Create(NULL,"Edit box");
}
int OnCreate(LPCREATESTRUCT lp)
{
RECT rect;
rect.top=10;
rect.left=10;
rect.right=130;
rect.bottom=30;
label.Create("Enter numbers",WS_CHILD|WS_VISIBLE|
WS_BORDER,rect,this);
rect.top=10;
rect.left=131;
rect.right=250;
rect.bottom=30;
edit_num.Create(WS_CHILD|WS_VISIBLE|
WS_BORDER,rect,this,EDIT_NUM);
edit_num.LimitText(10);
rect.top=40;
rect.left=110;
rect.right=150;
rect.bottom=60;
okbut.Create("&OK",WS_CHILD|WS_VISIBLE|WS_BORDER|
BS_PUSHBUTTON,rect,this,BUT_OK);
edit_num.SetFocus();
return 0;
}
void OnButOk()
{
char buff[25];
edit_num.GetWindowText(buff,25);
42
MessageBox(buff,"Data retrieved");
}
DECLARE_MESSAGE_MAP()
};
BEGIN_MESSAGE_MAP(mywin,CFrameWnd)
ON_COMMAND(BUT_OK,OnButOk)
ON_WM_CREATE()
END_MESSAGE_MAP()
class myapp:public CWinApp
{
public:
BOOL InitInstance()
{
mywin *p;
p=new mywin();
m_pMainWnd=p;
p->ShowWindow(SW_SHOWNORMAL);
return true;
}
};
myapp A;
Output:
43
Ex.No: 13
SDI Serialization
Date :
Aim:
To write a VC++ program to implement SDI Serialization
Logical Description:
Process of saving and restoring objects is called serialization. Implement
serialization for SDI applications
Algorithm:
1. Start the process
2. Create an object for myapp and invoke a method InitInstance( ) which calls
mywin( ).
3. Write a method to write into a file: OnWrite( ) in mywin class.
4. Write a method to read from a file : OnRead ( ) in the class mywin.
5. Map these methods to the members created.
6. Stop the process
Source Code:
// sdiDoc.cpp : implementation of the CSdiDoc class
#include "stdafx.h"
#include "sdi.h"
#include "sdiDoc.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CSdiDoc
IMPLEMENT_DYNCREATE(CSdiDoc, CDocument)
BEGIN_MESSAGE_MAP(CSdiDoc, CDocument)
//{{AFX_MSG_MAP(CSdiDoc)
44
// NOTE - the ClassWizard will add and remove mapping macros here.
// DO NOT EDIT what you see in these blocks of generated code!
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CSdiDoc construction/destruction
CSdiDoc::CSdiDoc()
{
// TODO: add one-time construction code here
}
CSdiDoc::~CSdiDoc()
{
}
BOOL CSdiDoc::OnNewDocument()
{
if (!CDocument::OnNewDocument())
return FALSE;
dx=50;
dy=50;
// TODO: add reinitialization code here
// (SDI documents will reuse this document)
return TRUE;
}
/////////////////////////////////////////////////////////////////////////////
// CSdiDoc serialization
void CSdiDoc::Serialize(CArchive& ar)
{
if (ar.IsStoring())
{
// TODO: add storing code here
ar<<dx<<dy;
//ar>>dx>>dy;
}
else
{
// TODO: add loading code here
//ar<<dx<<dy;
ar>>dx>>dy;
}
}
/////////////////////////////////////////////////////////////////////////////
// CSdiDoc diagnostics
#ifdef _DEBUG
void CSdiDoc::AssertValid() const
45
{
CDocument::AssertValid();
}
void CSdiDoc::Dump(CDumpContext& dc) const
{
CDocument::Dump(dc);
}
#endif //_DEBUG
/////////////////////////////////////////////////////////////////////////////
// CSdiDoc commands
Output:
46
Ex.No: 14
MDI Serialization
Date :
Aim:
To write a VC++ program to implement MDI serialization
Logical Description:
Process of saving and restoring objects is called serialization. Implement
serialization for MDI applications
Algorithm:
1. Start the process
2. Select MFC appwizard (Exe) and select multiple document in that.
3. Give next for further steps and finally click finish button
4. Create menu for read and write
5. For both read and write go to the class wizard, select command in that and write
the required codings
6. The document file will be available in the local space where we have started.
7. Execute the program
8. Stop the process
Source Code:
// serializationmdiView.cpp : implementation of the CSerializationmdiView class
#include "stdafx.h"
#include "serializationmdi.h"
#include "serializationmdiDoc.h"
#include "serializationmdiView.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CSerializationmdiView
47
IMPLEMENT_DYNCREATE(CSerializationmdiView, CView)
BEGIN_MESSAGE_MAP(CSerializationmdiView, CView)
//{{AFX_MSG_MAP(CSerializationmdiView)
ON_COMMAND(ID_WRITE, OnWrite)
ON_COMMAND(ID_READ, OnRead)
//}}AFX_MSG_MAP
// Standard printing commands
ON_COMMAND(ID_FILE_PRINT, CView::OnFilePrint)
ON_COMMAND(ID_FILE_PRINT_DIRECT, CView::OnFilePrint)
ON_COMMAND(ID_FILE_PRINT_PREVIEW, CView::OnFilePrintPreview)
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CSerializationmdiView construction/destruction
CSerializationmdiView::CSerializationmdiView()
{
// TODO: add construction code here
}
CSerializationmdiView::~CSerializationmdiView()
{
}
BOOL CSerializationmdiView::PreCreateWindow(CREATESTRUCT& cs)
{
// TODO: Modify the Window class or styles here by modifying
// the CREATESTRUCT cs
return CView::PreCreateWindow(cs);
}
/////////////////////////////////////////////////////////////////////////////
// CSerializationmdiView drawing
void CSerializationmdiView::OnDraw(CDC* pDC)
{
CSerializationmdiDoc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
// TODO: add draw code for native data here
}
/////////////////////////////////////////////////////////////////////////////
// CSerializationmdiView printing
BOOL CSerializationmdiView::OnPreparePrinting(CPrintInfo* pInfo)
{
// default preparation
return DoPreparePrinting(pInfo);
}
void CSerializationmdiView::OnBeginPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/)
48
{
// TODO: add extra initialization before printing
}
void CSerializationmdiView::OnEndPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/)
{
// TODO: add cleanup after printing
}
/////////////////////////////////////////////////////////////////////////////
// CSerializationmdiView diagnostics
#ifdef _DEBUG
void CSerializationmdiView::AssertValid() const
{
CView::AssertValid();
}
void CSerializationmdiView::Dump(CDumpContext& dc) const
{
CView::Dump(dc);
}
CSerializationmdiDoc* CSerializationmdiView::GetDocument() // non-debug version is
inline
{
ASSERT(m_pDocument-
>IsKindOf(RUNTIME_CLASS(CSerializationmdiDoc)));
return (CSerializationmdiDoc*)m_pDocument;
}
#endif //_DEBUG
/////////////////////////////////////////////////////////////////////////////
// CSerializationmdiView message handlers
void CSerializationmdiView::OnWrite()
{
CFile *f;
f = new CFile;
f->Open("D:mdi.txt", CFile::modeCreate|CFile ::modeWrite);
f->Write("Welcome to VC++", 15);
f->Close();
MessageBox("Data Written", "File Write");
}
void CSerializationmdiView::OnRead()
{
char x[100];
CFile *f;
49
f = new CFile;
f->Open("D:mdi.txt", CFile::modeRead);
DWORD size = f->GetLength();
f->Read(x, size);
f->Close();
CClientDC dc(this);
dc.TextOut(50,50, x, size);
}
Output:
50
Ex.No: 15
ODBC Connectivity
Date :
Aim:
To Write a VC++ program that implements database connectivity
Logical Description:
Implementing ODBC connectivity for a SDI application
Algorithm:
1. Create a database and table in MSAccess.
Goto MSACCESS,
 File->New->Blank database->Give database name(Students details)
 Inside that database create a table named stud with fields Roll no and
Name.
 Enter details for some five records ,save and exit.
2. Creating a DSN
 Goto Control Panel->click Data sources(ODBC)
 Click user DSN tab
 Click the Add button
 Double click Driver Do Microsoft Access(*.mdb)
 Give data source name as DSN1
 Select database(the location where u have stored ur students details
database)
 Click ok
 Now the DSN is created.
3. Run Appwizard(EXE) to create a SDI project named stud.
 Select Header files only option in step 2.
 Set CScrollView as class type in step 6.
4. Use class wizard
 Choose Add class->New->give class name(CStudSet) and set base
class name as CRecordSet.
 Click ok,it will show a Database options dialog box.
 In that select the DSN name and click Recordset type as dynaset,click
ok.
51
 It will ask u to select the table,select the table name stud,click ok.
5. Add the member variable to the class CstudDoc
CStudSet m_studSet;
6. Edit the studDoc.cpp file
Add the line #include “studSet.h” before the line #include “studDoc.h”.
7. Add the following private data member to the CstudView class.
CStudSet* m_pSet;
8. Edit the OnDraw and OnInitialUpdate functions in studView.cpp.
void CStudView::OnDraw(CDC* pDC)
{
TEXTMETRIC tm;
pDC->GetTextMetrics(&tm);
int nLineHeight=tm.tmHeight+tm.tmExternalLeading;
CPoint pText(0,0);
int y=0;
CString str;
if(m_pSet->IsBOF())
return;
m_pSet->MoveFirst();
while(!m_pSet->IsEOF()){
str.Format("%ld",m_pSet->m_Roll);
pDC->TextOut(pText.x,pText.y,str);
pDC->TextOut(pText.x+1000,pText.y,m_pSet->m_Name);
m_pSet->MoveNext();
pText.y-=nLineHeight;
}
}
void CStudView::OnInitialUpdate()
{
CScrollView::OnInitialUpdate();
CSize sizeTotal(8000,10500);
// TODO: calculate the total size of this view
SetScrollSizes(MM_HIENGLISH, sizeTotal);
m_pSet=&GetDocument()->m_studSet;
if(m_pSet->IsOpen())
m_pSet->Close();
m_pSet->Open();
}
52
Add the #include “studSet.h” before the line #include “studDoc.h”
9. Edit the stud.cpp file
Add #include “studSet.h” before the line #include “studDoc.h”
10. Build and run the application.
Output:
53
Ex.No: 16
Dynamic Link Library
Date :
Aim:
To calculate the simple interest using Dynamic Link Library (DLL).
Logical Description:
Dynamic Link Libraries(DLL):
 A DLL is a collection of small programs, any of which can be called when
needed by a large program that is running in the computer
 The advantage of DLL files is that, because they do not get loaded into RAM
together with the main program, space is saved in RAM. When and if a DLL file
is needed, then it is loaded and run.
 Examples As long as a user of MsWord is editing a document, the printer DLL
file does not need to be loaded into RAM.
 If the user decides to print the document, then the word application causes the
printer DLL file to be loaded and run.
 A DLL file is often given a “.DLL” file name .DLL files are dynamically linked
with the program that uses them during program execution rather then being
complied with the main program.
Algorithm:
1. Create a dynamic link library
2. Create the Client Program
3. Go to project ->settings->link tab->object/library modules->C:vc++dmDebug
dm.lib(Type the above said path)
4. Now copy the .DLL file which has been created in the C:vc++dmDebug to the
client program in the path C:vc++dc.
5. Compile the Client Application and run the application. Click on the calculate
button to view the result in the last edit control.
Source Code:
54
MYClass.cpp
Float CMYClass :: interest(float p, float n, float r)
{
return(p*n*r/100);
}
dcDlg.h
#include ”c:vc++dmMyClass.h”
public:
CMyClass objclass;
Include the following lines in dcDlg.cpp
void dcDlg::OnButton1() {
UpdateData(true)
m_res=objclass.interest(m_p,m_n,m_r);
UpdateData(false);
}
void dcDlg::On Button2() {
PostQuitMessage(0);
}
Output:
55
Ex.No: 17
Document / View Architecture
Date :
Aim:
To write a VC++ program to implements Document / View architecture
Logical Description:
Implementing Document / View Architecture for SDI applications and creating
some drawing objects
Algorithm:
1. Start the process
2. Create an object for myapp calss. Using he object allocate memory to the mywin
class and call the constructor.
3. mywin class inherits the properties of CFrameWnd class
4. Draw some objects using message handler
5. Execute the program
6. Stop the process
Source Code:
sdisquaresDoc.h header file
//Implementation
public:
void SetSquare(int i,int j,COLORREF color);
COLORREF GetSquare(int i,int j);
COLORREF GetCurrentColor();
Virtual ~CsdisquaresDoc();
//Generated messagemap functions
prortected:
COLORREF m_clrCurrentColor;
COLORREF m_clrGrid[4][4];
//{{AFX_MSG(CsdisquaresDoc)
afx_msg void OnColorRed();
afx_msg void OnColorGreen();
afx_msg void OnColorBlue();
afx_msg void OnColorWhite();
56
//}}AFX_MSG
sdisquaresDoc.cpp
BEGIN_MESSAGE_MAP( )
//{{AFX_MSG_MAP( )
ON_COMMAND(ID_COLOR_RED,OnColorRed)
ON_COMMAND(ID_COLOR_BLUE,OnColorBlue)
ON_COMMAND(ID_COLOR_GREEN,OnColorGreen)
ON_COMMAND(ID_COLOR_WHITE,OnColorWhite)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
BOOL CsdisquaresDoc::OnNewDocument()
{
if(!CDocument::OnNewDocument())
return FALSE;
for(int i=0;i<4;i++)
for(j=0;j<4;j++)
m_clrGrid[i][j]=RGB(255,255,255);
m_clrCurrentColor=RGB(255,0,0);
return TRUE;
}
void CsdisquaresDoc::Serialize(CArchive &ar)
{
if(ar.IsStoring())
{
for(int i=0;i<4;i++)
for(int j=0;j<4;j++)
ar<<m_clrGrid[i][j];
ar<<m_clrCurrentColor;
}
else
{
for(int i=0;i<4;i++)
for(int j=0;j<4;j++)
ar>>m_clrGrid[i][j];
ar>>m_clrCurrentColor;
}
}
//CsdisquaresDoc commands
COLORREF Csdisquares::GetCurrentColor()
57
{
return m_clrCurrentColor;
}
COLORREF csdisquaresDoc::GetSquare(int I,int j)
{
ASSERT(i>=0&&i<=3&&j>=0&&j<=3);
Return m_clrGrid[i][j];
}
void CsdisquaresDoc::SetSquare(int i,int j,COLORREF color)
{
ASSERT(i>=0&&i<=3&&j>=0&&j<=3);
M_clrGrid[i][j]=color;
SetModifiedFlag(TRUE);
UpdateAllViews(NULL);
}
void CsdisquaresDoc::OnColorRed()
{
m_clrCurrentColor=RGB(255,0,0);
}
void CsdisquaresDoc::OnColorGreen()
{
m_clrCurrentColor=RGB(0,255,0);
}
void CsdisquaresDoc::OnColorBlue()
{
m_clrCurrentColor=RGB(0,0,255);
}
void CsdisquaresDoc::OnColorWhite()
{
m_clrCurrentColor=RGB(255,255,255);
}
sdisquaresview.h header file
//{{AFX_MSG( )
afx_msg void OnLButtonDown(UINT nFlags,CPoint point);
//}}AFX_MSG
sdisquaresview.cpp
BEGIN_MESSAGE_MAP( )
//{{AFX_MSG( )
ON_WM_LBUTTONDOWN()
//}}AFX_MSG_MAP
58
void Csdisquaresview::OnDraw(CDC* pDC)
{
CsdisquaresDoc* pDoc=GetDocument();
ASSERT_VALID(pDoc);
pDC->SetMapMode(MM_LOENGLISH);
//Draw 16 squares
for(int i=0;i<4;i++){
for(int j=0;j<4;j++){
COLORREF color=pDoc->GetSquare(i,j);
CBrush brush(color);
int x1=(j*100)+50;
int y1=(i*-100)-50;
int x2=x1+100;
int y2=y1-100;
CRect rect(x1,y1,x2,y2);
pDC->FillRect(rect,&Brush);
}
}
//Draw grid lines around them
for(int x=50;x<=450;x+=100){
pDC->MoveTo(x,-50);
pDC->LineTo(x,-450);
}
for(int y=-50;y>=-450;y-=100){
pDC->MoveTo(50,y);
pDC->LineTo(450,y);
}
}
void Csdisquaresview::OnLButtonDown(UINT nFlags,CPoint point)
{
Cview::OnLButtonDown(nFlags,point);
CClientDC dc(this);
dc.SetMapMode(MM_LOENGLISH);
CPoint pos=point;
dc.DPtoLP(&pos);
//if the square was clicked,set its color to the current color
if(pos.x>=50&&pos.x<=450&&pos.y<=-50&&pos.y>=-450){
int i=(-pos.y-50)/100;
int j=(pos.x-50)/100;
CsdisquaresDoc* pDoc=GetDocument();
COLORREF clrCurrentColor=pDoc->GetCurrentColor();
pDoc->SetSquare(i,j,clrCurrentColor);
}
}
59
Output:
60

More Related Content

PDF
openFrameworks – 関数・クラス、オブジェクト指向プログラミング導入 - 多摩美メディアアートII
PDF
C++ Windows Forms L09 - GDI P2
PPTX
PPTX
MFC Message Handling
PPTX
15年前のMFC
PPTX
Visual programming
PDF
First7124911 visual-cpp-and-mfc-programming
PDF
C++ Windows Forms L08 - GDI P1
openFrameworks – 関数・クラス、オブジェクト指向プログラミング導入 - 多摩美メディアアートII
C++ Windows Forms L09 - GDI P2
MFC Message Handling
15年前のMFC
Visual programming
First7124911 visual-cpp-and-mfc-programming
C++ Windows Forms L08 - GDI P1

Similar to Visual C++ lab manual MC1755-VC++ - L-LM.doc (20)

PPT
introduction to_mfc
PPT
VC++ Fundamentals
PPT
Vc++ 3
PDF
Of class1
PPT
Design Patterns By Sisimon Soman
PDF
Bridge Pattern
PPTX
31csharp
PPTX
PPTX
Shape12 6
PDF
Visual programming lab
PPT
DOC
Visual C++ questions MC1755-VC++ - L-VVQ.doc
PDF
Programming using opengl in visual c++
TXT
KEY
Sbaw090623
PPTX
Beginning direct3d gameprogramming01_20161102_jintaeks
PDF
PDF
Artyom Shishkin - Printing interception via modifying Windows GDI
PDF
02 direct3 d_pipeline
PDF
#include iostream #includeData.h #includePerson.h#in.pdf
introduction to_mfc
VC++ Fundamentals
Vc++ 3
Of class1
Design Patterns By Sisimon Soman
Bridge Pattern
31csharp
Shape12 6
Visual programming lab
Visual C++ questions MC1755-VC++ - L-VVQ.doc
Programming using opengl in visual c++
Sbaw090623
Beginning direct3d gameprogramming01_20161102_jintaeks
Artyom Shishkin - Printing interception via modifying Windows GDI
02 direct3 d_pipeline
#include iostream #includeData.h #includePerson.h#in.pdf
Ad

More from AnonymousRuslwNZZl (7)

DOC
Visual c++ lab plan MC1755-VC++-L-LP.doc
DOC
Database management MC9218-DBMS-L-QB.doc
DOC
Database Management S MC9218-DBMS-L-LM.doc
DOC
Design and analysis of algorithm MC9229-DAA-L-LM.doc
PPTX
MS Excel and it’s basic functions.pptx
PPTX
GIMP Tutorial.pptx
DOCX
python programs .docx
Visual c++ lab plan MC1755-VC++-L-LP.doc
Database management MC9218-DBMS-L-QB.doc
Database Management S MC9218-DBMS-L-LM.doc
Design and analysis of algorithm MC9229-DAA-L-LM.doc
MS Excel and it’s basic functions.pptx
GIMP Tutorial.pptx
python programs .docx
Ad

Recently uploaded (20)

PPTX
Chinmaya Tiranga Azadi Quiz (Class 7-8 )
PDF
AI-driven educational solutions for real-life interventions in the Philippine...
PPTX
20th Century Theater, Methods, History.pptx
PPTX
Computer Architecture Input Output Memory.pptx
PPTX
202450812 BayCHI UCSC-SV 20250812 v17.pptx
PPTX
A powerpoint presentation on the Revised K-10 Science Shaping Paper
PDF
BP 704 T. NOVEL DRUG DELIVERY SYSTEMS (UNIT 1)
PPTX
TNA_Presentation-1-Final(SAVE)) (1).pptx
PPTX
CHAPTER IV. MAN AND BIOSPHERE AND ITS TOTALITY.pptx
PDF
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
PDF
احياء السادس العلمي - الفصل الثالث (التكاثر) منهج متميزين/كلية بغداد/موهوبين
PPTX
Introduction to pro and eukaryotes and differences.pptx
PDF
Computing-Curriculum for Schools in Ghana
PDF
medical_surgical_nursing_10th_edition_ignatavicius_TEST_BANK_pdf.pdf
PPTX
B.Sc. DS Unit 2 Software Engineering.pptx
PDF
Weekly quiz Compilation Jan -July 25.pdf
PDF
My India Quiz Book_20210205121199924.pdf
PDF
MBA _Common_ 2nd year Syllabus _2021-22_.pdf
PDF
FOISHS ANNUAL IMPLEMENTATION PLAN 2025.pdf
PDF
Empowerment Technology for Senior High School Guide
Chinmaya Tiranga Azadi Quiz (Class 7-8 )
AI-driven educational solutions for real-life interventions in the Philippine...
20th Century Theater, Methods, History.pptx
Computer Architecture Input Output Memory.pptx
202450812 BayCHI UCSC-SV 20250812 v17.pptx
A powerpoint presentation on the Revised K-10 Science Shaping Paper
BP 704 T. NOVEL DRUG DELIVERY SYSTEMS (UNIT 1)
TNA_Presentation-1-Final(SAVE)) (1).pptx
CHAPTER IV. MAN AND BIOSPHERE AND ITS TOTALITY.pptx
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
احياء السادس العلمي - الفصل الثالث (التكاثر) منهج متميزين/كلية بغداد/موهوبين
Introduction to pro and eukaryotes and differences.pptx
Computing-Curriculum for Schools in Ghana
medical_surgical_nursing_10th_edition_ignatavicius_TEST_BANK_pdf.pdf
B.Sc. DS Unit 2 Software Engineering.pptx
Weekly quiz Compilation Jan -July 25.pdf
My India Quiz Book_20210205121199924.pdf
MBA _Common_ 2nd year Syllabus _2021-22_.pdf
FOISHS ANNUAL IMPLEMENTATION PLAN 2025.pdf
Empowerment Technology for Senior High School Guide

Visual C++ lab manual MC1755-VC++ - L-LM.doc

  • 1. Department of Computer Applications Lab Manual MC1755 – Visual Programming (IV Semester) Prepared by: Ms. V.Kayathri Ms. N.M. Kavitha & Ms.G.Padmavathy (Lect. / MCA) (Lect. / MCA) RAJALAKSHMI ENGINEERING COLLEGE Rajalakshmi Nagar, Thandalam, Chennai – 602 105 1
  • 2. List of Lab Exercises Sl. No. Exercise Page No. 1. Window Creation 2. Message Map Functions 3. Graphical Device Interface 4. Single Document Interface 5. Multiple Document Interface 6. Toolbar Creation 7. Status bar Creation 8. Menu bar Creation 9. Modal Dialog Box Creation 10. Modeless Dialog Box Creation 11. Model Dialog Box creation – Student Details 12. Dynamic Controls 13. SDI Serialization 14. MDI serialization 15. ODBC connectivity 16. Dynamic Link Library 17. Document View Architecture 2
  • 3. Ex.No: 1 Window Creation Date : Aim: To write a Visual C++ program for creating a window using win32 application. Logical Description: The program starts with object creation. After initializing the instance, the user created window is assigned as main window. Using Show window option project user created window. Algorithm: 1. Start the Process 2. Create an object for an class which inherits CWinApp 3. The object access InitInstance() function 4. Create a pointer object for the class which inherits CFrameWindow by allocating the memory to the object 5. Show the created window using SW_SHOWNORMAL 6. Stop the process Source Code: #include<afxwin.h> class mywnd : public CFrameWnd { public: mywnd() { Create(0, "My window"); } }; class myapp: public CWinApp { public : BOOL InitInstance() { mywnd *p; p = new mywnd; m_pMainWnd = p ; // main thread 3
  • 5. Ex.No: 2 Message Map Functions Date : Aim: To write a Visual C++ program which uses message map functions using win32 application. Logical Description: The program starts with object creation. After initializing the instance, the user created window is assigned as main window. Using Show window option project user created window. Using message map option draw circles when ever mouse moves on the client area. Algorithm: 1. Start the Process 2. Create an object for a myapp class. Invoke InitInstance function and create object for mywin to call the constructor mywin. 3. A window is created by calling the create function which resides inside the constructor 4. Inside message map write the code for draw circle inside the view window. 5. Show the created window using SW_SHOWNORMAL 6. Stop the process Source Code: #include<afxwin.h> class mywin :public CFrameWnd { public: mywin() { Create(0,"MFC"); } DECLARE_MESSAGE_MAP() void OnMouseMove(UINT f,CPoint p) { CClientDC dc(this); 5
  • 6. dc.Ellipse(p.x,p.y,p.x+50,p.y+50); } }; BEGIN_MESSAGE_MAP(mywin,CFrameWnd) ON_WM_MOUSEMOVE() END_MESSAGE_MAP() class myapp : public CWinApp { public: BOOL InitInstance() { mywin *p; p = new mywin(); m_pMainWnd = p; p->ShowWindow(SW_SHOWNORMAL); return TRUE; } }; myapp A; Output: 6
  • 7. Ex.No: 3 Graphical Device Interface Date : Aim: To write a Visual C++ program which uses the GDI tools Logical Description: The program starts with object creation. After initializing the instance, the user created window is assigned as main window. Using Show window option project user created window. Using message map create a pen & brush. Using that pen & brush draw objects. Algorithm: 1. Start the Process 2. Create an object for an myapp class. Invoke InitInstance function and create object for mywin to call the constructor mywin. 3. A window is created by calling the create function which resides inside the constructor 4. Inside message map write the code for GDI objects like pen & brush . 5. Show the created window using SW_SHOWNORMAL 6. Stop the process Source Code: #include <afxwin.h> class mywnd : public CFrameWnd { public: mywnd() { Create(0,"MFC"); } DECLARE_MESSAGE_MAP() void OnLButtonDown(UINT f,CPoint p) { CPen pen; CBrush brush; 7
  • 8. CClientDC dc(this); pen.CreatePen(PS_SOLID, 5,RGB(200,120,130)); brush.CreateHatchBrush(HS_VERTICAL,RGB(50,50,130)); dc.SelectObject(pen); dc.SelectObject(brush); dc.Rectangle(200,200,300,300); } void OnRButtonDown(UINT f,CPoint p) { CPen pen; CBrush brush; CClientDC dc(this); pen.CreatePen(PS_SOLID, 5,RGB(123,134,130)); brush.CreateHatchBrush(HS_HORIZONTAL,RGB(150,150,230)); dc.SelectObject(pen); dc.SelectObject(brush); dc.Rectangle(50,50,200,200); } }; BEGIN_MESSAGE_MAP(mywnd,CFrameWnd) ON_WM_LBUTTONDOWN() ON_WM_RBUTTONDOWN() END_MESSAGE_MAP() class myapp : public CWinApp { public: BOOL InitInstance() { mywnd *p; p = new mywnd(); m_pMainWnd = p; p->ShowWindow(SW_SHOWNORMAL); return true; } }; myapp A; 8
  • 10. Ex.No: 4 Single Document Interface Date : Aim: To create a SDI (Application Wizard) and to draw an ellipse inside the view window using Device Context. Logical Description: Using wizards create a single document interface Algorithm: 1. File – New – Projects tab – MFC Appwizard (exe) – Give the location name and the project name – ok 2. Select single Document option. 3. Accept the defaults in the next four screens. 4. Click the finish button – ok button. [ProgramnameView.cpp and ProgramnameView.h files define the CprogramnameView class, which is central to the application ] 5. In the .cpp file , write the following code in the OnDraw function void CprogramnameView :: OnDraw(CDC *pDC) PDC  TextOut(0,0, “Hello World “); PDC  SelectStockObject(GRAY_BRUSH); PDC  Ellipse(CRect(0,20,100,120)); These 3 are the member functions of the application framework’s device context class CDC. 6. Build and execute the Application. Source Code: // sdiView.cpp : implementation of the CSdiView class // #include "stdafx.h" #include "sdi.h" 10
  • 11. #include "sdiDoc.h" #include "sdiView.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CSdiView IMPLEMENT_DYNCREATE(CSdiView, CView) BEGIN_MESSAGE_MAP(CSdiView, CView) //{{AFX_MSG_MAP(CSdiView) // NOTE - the ClassWizard will add and remove mapping macros here. // DO NOT EDIT what you see in these blocks of generated code! //}}AFX_MSG_MAP // Standard printing commands ON_COMMAND(ID_FILE_PRINT, CView::OnFilePrint) ON_COMMAND(ID_FILE_PRINT_DIRECT, CView::OnFilePrint) ON_COMMAND(ID_FILE_PRINT_PREVIEW, CView::OnFilePrintPreview) END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CSdiView construction/destruction CSdiView::CSdiView() { // TODO: add construction code here } CSdiView::~CSdiView() { } BOOL CSdiView::PreCreateWindow(CREATESTRUCT& cs) { // TODO: Modify the Window class or styles here by modifying // the CREATESTRUCT cs return CView::PreCreateWindow(cs); } 11
  • 12. ///////////////////////////////////////////////////////////////////////////// // CSdiView drawing void CSdiView::OnDraw(CDC* pDC) { CSdiDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); pDC->TextOut(0,0,"Hello world"); pDC->SelectStockObject(GRAY_BRUSH); pDC->Ellipse(CRect(0,20,100,120)); } ///////////////////////////////////////////////////////////////////////////// // CSdiView printing BOOL CSdiView::OnPreparePrinting(CPrintInfo* pInfo) { // default preparation return DoPreparePrinting(pInfo); } void CSdiView::OnBeginPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/) { // TODO: add extra initialization before printing } void CSdiView::OnEndPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/) { // TODO: add cleanup after printing } ///////////////////////////////////////////////////////////////////////////// // CSdiView diagnostics #ifdef _DEBUG void CSdiView::AssertValid() const { CView::AssertValid(); } void CSdiView::Dump(CDumpContext& dc) const { CView::Dump(dc); } 12
  • 13. CSdiDoc* CSdiView::GetDocument() // non-debug version is inline { ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CSdiDoc))); return (CSdiDoc*)m_pDocument; } #endif //_DEBUG ///////////////////////////////////////////////////////////////////////////// // CSdiView message handlers Output: 13
  • 14. Ex.No: 5 Multiple Document Interface Date : Aim: To create a MDI (Application Wizard) and to draw an ellipse inside the view window using Device Context. Logical Description: Using wizards create a multiple document interface Algorithm: 1. File – New – Projects tab – MFC Appwizard (exe) – Give the location name and the project name – ok 2. Select Multiple Document option. 3. Accept the defaults in the next four screens. 4. Click the finish button – ok button. [ProgramnameView.cpp and ProgramnameView.h files define the CprogramnameView class, which is central to the application ] 5. In the .cpp file , write the following code in the OnDraw function void CprogramnameView :: OnDraw(CDC *pDC) PDC  TextOut(0,0, “Hello World “); PDC  SelectStockObject(GRAY_BRUSH); PDC  Ellipse(CRect(0,20,100,120)); These 3 are the member functions of the application framework’s device context class CDC. 6. Build and execute the Application. Source Code: // mdiView.cpp : implementation of the CMdiView class #include "stdafx.h" #include "mdi.h" #include "mdiDoc.h" 14
  • 15. #include "mdiView.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CMdiView IMPLEMENT_DYNCREATE(CMdiView, CView) BEGIN_MESSAGE_MAP(CMdiView, CView) //{{AFX_MSG_MAP(CMdiView) // NOTE - the ClassWizard will add and remove mapping macros here. // DO NOT EDIT what you see in these blocks of generated code! //}}AFX_MSG_MAP // Standard printing commands ON_COMMAND(ID_FILE_PRINT, CView::OnFilePrint) ON_COMMAND(ID_FILE_PRINT_DIRECT, CView::OnFilePrint) ON_COMMAND(ID_FILE_PRINT_PREVIEW, CView::OnFilePrintPreview) END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CMdiView construction/destruction CMdiView::CMdiView() { // TODO: add construction code here } CMdiView::~CMdiView() { } BOOL CMdiView::PreCreateWindow(CREATESTRUCT& cs) { // TODO: Modify the Window class or styles here by modifying // the CREATESTRUCT cs return CView::PreCreateWindow(cs); } ///////////////////////////////////////////////////////////////////////////// // CMdiView drawing 15
  • 16. void CMdiView::OnDraw(CDC* pDC) { CMdiDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); pDC->TextOut(0,0, "Hello World "); pDC->SelectStockObject(GRAY_BRUSH); pDC->Ellipse(CRect(0,20,100,120)); } ///////////////////////////////////////////////////////////////////////////// // CMdiView printing BOOL CMdiView::OnPreparePrinting(CPrintInfo* pInfo) { // default preparation return DoPreparePrinting(pInfo); } void CMdiView::OnBeginPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/) { // TODO: add extra initialization before printing } void CMdiView::OnEndPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/) { // TODO: add cleanup after printing } ///////////////////////////////////////////////////////////////////////////// // CMdiView diagnostics #ifdef _DEBUG void CMdiView::AssertValid() const { CView::AssertValid(); } void CMdiView::Dump(CDumpContext& dc) const { CView::Dump(dc); } CMdiDoc* CMdiView::GetDocument() // non-debug version is inline { 16
  • 18. Ex.No: 6 Tool bar Creation Date : Aim: To write a VC++ program to create a toolbar which displays different shapes when the buttons are clicked from tool bar. Logical Description: The program starts with object creation. After initializing the instance, the user created window is assigned as main window. Using Show window option project user created window. Using resources option create a toolbar & attach it to the user created window. Algorithm: 1. Start the process 2. Create 4 buttons for displaying circle, rectangle, square and exit by inserting resources and saving them with their respective names. 3. Create 4 functions to its corresponding IDs draw 4. Map these 4 functions to its corresponding IDs. 5. Create a tool bar tab from its base class CToolBar in a function names OnCreate(). 6. Allocate memory space for toolbar 7. Load the tool bar and create it using the functions load toolbar and enable docking. 8. Set the style of the toolbar by using SetBarStyle functions 9. Stop the process Source Code: #include<afxwin.h> #include<afxext.h> #include "resource.h" class mywin:public CFrameWnd { public: 18
  • 19. mywin() { Create(0,"TOOLBAR"); } DECLARE_MESSAGE_MAP() void OnExit() { PostQuitMessage(0); } void OnCir() { CClientDC dc(this); dc.Ellipse(50,50,100,100); } void OnRect() { CClientDC dc(this); CPen pen; CBrush brush; dc.Rectangle(220,220,300,250); pen.CreatePen(PS_SOLID,3,RGB(250,0,0)); brush.CreateSolidBrush(RGB(340,240,75)); dc.SelectObject(pen); dc.SelectObject(brush); } void OnSqu() { CClientDC dc(this); dc.Rectangle(150,150,200,200); } int OnCreate(LPCREATESTRUCT lp) { CToolBar *tb; tb=new CToolBar(); tb->Create(this); tb->LoadToolBar(MAKEINTRESOURCE(IDR_TOOLBAR1)); EnableDocking(CBRS_ALIGN_ANY); tb->EnableDocking(CBRS_ALIGN_ANY); tb->SetBarStyle(tb->GetBarStyle()|CBRS_TOOLTIPS); DockControlBar(tb); return true; } }; BEGIN_MESSAGE_MAP(mywin,CFrameWnd) ON_COMMAND(ID_CIRCLE,OnCir) ON_COMMAND(ID_RECTANGLE,OnRect) 19
  • 20. ON_COMMAND(ID_SOUARE,OnSqu) ON_COMMAND(ID_EXIT,OnExit) ON_WM_CREATE() END_MESSAGE_MAP() class myapp:public CWinApp { public: BOOL InitInstance() { mywin *p; p=new mywin(); m_pMainWnd=p; p->ShowWindow(SW_SHOWNORMAL); return true; } }; myapp A; Output: 20
  • 21. Ex.No: 7 Status bar Creation Date : Aim: To write a VC++ program to create a window which contains status bar Logical Description: The program starts with object creation. After initializing the instance, the user created window is assigned as main window. Using Show window option project user created window. Using resources option create a statusbar & attach it to the user created window. Algorithm: 1. Start the process 2. Initially control starts from object creation 3. Then it calls the myapp class which has the main function is which constructor is invoked using the pointer variable. 4. Constructor mywin then creates the window 5. After the DECLARE_MESSAGE_MAP macro, specify the codeing for message handlers. OnMyRect(), OnMysquare(), OnMyCircle() and OnMyExit(). 6. In the OnCreate message handler, specify the status bar base class, create an instance of it and use the instance of it and use the instance to create the status bar 7. Next define the messages corresponding to the message handlers defines above then assign the user created window as the main window and project the same using show window 8. Finally when the user moves the mouse on the options corresponding message appears on status bar and on selection of the option, the corresponding figure is displayed 9. Stop the process 21
  • 22. Source Code: #include<afxwin.h> #include<afxext.h> #include"resource.h" class mywin : public CFrameWnd { public : mywin() { Create(0,"MFC",WS_OVERLAPPEDWINDOW, CRect(100,100,600,500),0, MAKEINTRESOURCE(IDR_MENU1)); } DECLARE_MESSAGE_MAP() int OnCreate(LPCREATESTRUCT lp) { UINT panes[] = {0,0,ID_INDICATOR_CAPS, ID_INDICATOR_NUM,ID_INDICATOR_SCRL}; CStatusBar *sb; sb = new CStatusBar(); sb->Create(this); sb->SetIndicators(panes,5); return 0; } void OnMyExit() { PostQuitMessage(0); } }; BEGIN_MESSAGE_MAP(mywin,CFrameWnd) ON_COMMAND(ID_EXIT,OnMyExit) ON_WM_CREATE() END_MESSAGE_MAP() class myapp : public CWinApp { public: BOOL InitInstance() { mywin *p; p = new mywin(); 22
  • 24. Ex.No: 8 Menu bar creation Date : Aim: To write a VC++ program to create a menu bar which displays when the menu items are selected from the menu bar Logical Description: The program starts with object creation. After initializing the instance, the user created window is assigned as main window. Using Show window option project user created window. Using resources option create a menu bar & attach it to the user created window. Algorithm: 1. Start the process 2. Create a tool bar tab from its base class CToolbar in a function name OnCreate(). 3. Create 4 buttons for displaying circle, rectangle, square and exit by inserting resources and saving them with their respective names 4. Create 4 functions to its corresponding IDs draw 5. Map these 4 functions to its corresponding IDs 6. Allocate memory space for tool bar 7. Load the tool bar and create it using the functions load tool bar and enable docking 8. Set the style of the tool bar by using SetBarStyle function 9. After the DECLARE_MESSAGE_MAP macro, specify the coding for message handlers. OnRect(), OnSquare(), OnCircle() and OnExit() 10. Load the tool bar 11. Stop the process 24
  • 25. Source Code: #include<afxwin.h> #include"resource.h" class myframe:public CFrameWnd { public: int u,u1,u2,u3; COLORREF b; myframe() { Create(0,"DRAWINGS",WS_OVERLAPPED | WS_SYSMENU,CRect(0,0,500,500),0,MAKEINTRESOURCE(IDR_MENU1)); } void OnPaint(); void Rectangle() { u =1; Invalidate(); } void Circle() { u =2; Invalidate(); } void Ellipse() { u =3; Invalidate(); } void Square() { u =4; Invalidate(); } void Line() { u =5; Invalidate(); } void Solid() { u2 =1; Invalidate(); } void Dash() 25
  • 26. { u2 =2; Invalidate(); } void Dashdot() { u2 = 3; Invalidate(); } void Cross() { u3 = 1; Invalidate(); } void Diagonal() { u3 =2; Invalidate(); } void Fdiagonal() { u3 =3; Invalidate(); } void Red() { u1 =1; Invalidate(); } void Green() { u1 =2; Invalidate(); } void Blue() { u1 =3; Invalidate(); } DECLARE_MESSAGE_MAP() }; BEGIN_MESSAGE_MAP(myframe,CFrameWnd) ON_COMMAND(ID_RECT,Rectangle) ON_COMMAND(ID_CIR,Circle) ON_COMMAND(ID_ELL,Ellipse) ON_COMMAND(ID_SQR,Square) 26
  • 27. ON_COMMAND(ID_LIN,Line) ON_COMMAND(ID_R,Red) ON_COMMAND(ID_G,Green) ON_COMMAND(ID_B,Blue) ON_COMMAND(121,Solid) ON_COMMAND(122,Dash) ON_COMMAND(123,Dashdot) ON_COMMAND(131,Cross) ON_COMMAND(132,Diagonal) ON_COMMAND(133,Fdiagonal) ON_WM_PAINT() END_MESSAGE_MAP() void myframe::OnPaint() { int bst = 0; switch(u3) { case 1: bst = HS_CROSS; break; case 2: bst = HS_BDIAGONAL; break; case 3: bst = HS_FDIAGONAL; break; } switch(u1) { case 1: b = RGB(255,0,0); break; case 2: b = RGB(0,255,0); break; case 3: b = RGB(0,0,255); break; } int pst = 0; switch(u2) { case 1: 27
  • 28. pst = PS_SOLID; break; case 2: pst = PS_DASH; break; case 3: pst = PS_DASHDOT; break; } CPaintDC dc(this); CPen p; p.CreatePen(pst,1,RGB(0,0,0)); CBrush br(bst,b); dc.SelectObject(&br); dc.SelectObject(&p); switch(u) { case 1: dc.Rectangle(70,100,400,300); break; case 2: dc.Ellipse(300,300,150,150); break; case 3: dc.Ellipse(300,300,200,100); break; case 4: dc.Rectangle(100,100,200,200); break; case 5: dc.MoveTo(200,200); dc.LineTo(400,400); break; } } class myapp:public CWinApp { public: BOOL InitInstance() { myframe *p; p = new myframe(); m_pMainWnd = p; p->ShowWindow(SW_SHOWNORMAL); return TRUE; } 28
  • 30. Ex.No: 9 Modal Dialog box Creation Date : Aim: To write a VC++ program for creating a modal dialog box Logical Description: The program starts with object creation. After initializing the instance, the user created window is assigned as main window. Using Show window option project user created window. Using resources option create a Modal dialog box & attach it to the user created window. Algorithm: 1. Start the process 2. Initially control starts from object creation 3. Create a dialog box of type modal 4. using IDD_DIALOG1 crate a new dialog box and add the items in it 5. Type cast te allocated memory obtained using GetDlgItem() function into CListBox and assign it to lb which is of type CListBox 6. Add the data given in the edit box IDC_EDIT1 into the listbox IDC_LIST1 using a user created add function 7. Remove the data given in the list box IDC_LIST1 by clicking remove button which is actually a user defined function 8. Stop the process Source Code: #include<afxwin.h> #include<afxdlgs.h> #include "resource.h" class mydlg:public CDialog { private: CListBox *lb; public: 30
  • 31. mydlg():CDialog(IDD_DIALOG1) { } public: BOOL OnInitDialog() { SetDlgItemText(IDC_EDIT1,"Welcome"); lb=(CListBox*)GetDlgItem(IDC_LIST1); lb->AddString("Chennai"); lb->AddString("Erode"); lb->AddString("Trichy"); lb->AddString("Coimbatore"); return TRUE; } void OnOK() { EndDialog(TRUE); } void OnCancel() { EndDialog(FALSE); } void OnMyAdd() { char st[100]; GetDlgItemText(IDC_EDIT1, st,100); lb->AddString(st); } void OnMyDel() { int s; s = lb->GetCurSel(); if (s>= 0) lb->DeleteString(s); } DECLARE_MESSAGE_MAP() }; BEGIN_MESSAGE_MAP(mydlg,CDialog) ON_COMMAND(IDC_ADD,OnMyAdd) ON_COMMAND(IDC_DEL,OnMyDel) END_MESSAGE_MAP() 31
  • 32. class mywin:public CFrameWnd { public: mywin() { Create(0,"MFC WINDOW"); } void OnRButtonDown(UINT f,CPoint p) { mydlg dlg; dlg.DoModal(); } DECLARE_MESSAGE_MAP() }; BEGIN_MESSAGE_MAP(mywin,CFrameWnd) ON_WM_RBUTTONDOWN() END_MESSAGE_MAP() class myapp:public CWinApp { public: BOOL InitInstance() { mywin *p; p=new mywin(); m_pMainWnd=p; p->ShowWindow(SW_SHOWNORMAL); return true; } }; myapp A; 32
  • 34. Ex.No: 10 Modeless Dialog box Creation Date : Aim: To write a VC++ program to display the text on modeless dialog box Logical Description: The program starts with object creation. After initializing the instance, the user created window is assigned as main window. Using Show window option project user created window. Using resources option create a Modeless dialog box & attach it to the user created window. Algorithm: 1. Start the process 2. Create a dialog box using IDD_DIALOG1 and add the items in it 3. The creation of the dialog box can be done with the help of CDialog creating an instance to it. 4. Allocate memory to the created instance 5. Call the create method (creation of instance) on the event RButtonDown 6. Stop the process Source Code: #include<afxwin.h> #include<afxdlgs.h> #include "resource.h" class mydlg:public CDialog { public: mydlg():CDialog() { } public: BOOL OnInitDialog() 34
  • 35. { return TRUE; } void OnOK() { EndDialog(TRUE); } void OnCancel() { EndDialog(FALSE); } DECLARE_MESSAGE_MAP() }; BEGIN_MESSAGE_MAP(mydlg,CDialog) ON_COMMAND(IDC_CIRCLE, OnCircle) ON_COMMAND(IDC_SQUARE, OnSquare) END_MESSAGE_MAP() class mywin:public CFrameWnd { public: mywin() { Create(0,"MFC WINDOW"); } void OnRButtonDown( ) { CDialog *dlg; dlg = new mydlg(); dlg->Create(IDD_DIALOG1); dlg->ShowWindow(1); } DECLARE_MESSAGE_MAP() }; BEGIN_MESSAGE_MAP(mywin,CFrameWnd) ON_WM_RBUTTONDOWN() END_MESSAGE_MAP() class myapp:public CWinApp { 35
  • 36. public: BOOL InitInstance() { mywin *p; p=new mywin(); m_pMainWnd=p; p->ShowWindow(SW_SHOWNORMAL); return true; } }; myapp A; Output: 36
  • 37. Ex.No: 11 Modal Dialog box Creation – Student Details Date : Aim: To write a VC++ program to display the text on modeless dialog box Logical Description: The program starts with object creation. After initializing the instance, the user created window is assigned as main window. Using Show window option project user created window. Using resources option create a Modeless dialog box & attach it to the user created window. Algorithm: 1. Start the process 2. Create a dialog box using IDD_DIALOG1 and add the items in it 3. The creation of the dialog box can be done with the help of CDialog creating an instance to it. 4. Allocate memory to the created instance 5. Call the create method (creation of instance) on the event RButtonDown 6. Stop the process Source Code: #include<afxwin.h> #include<afxdlgs.h> #include”resource.h” class mydialog::public CDialog { public: mydialog():CDialog(IDD_DIALOG1) { } BOOL OnInitDialog() { SetDlgItemText(IDC_EDIT1, “”); SetDlgItemText(IDC_EDIT2, “”); CheckRadioButton(IDC_RADIO1,IDC_RADIO2,IDC_RADIO3); CheckDlgButton(IDC_CHECK1,0); 37
  • 38. CheckDlgButton(IDC_CHECK2,0); CheckDlgButton(IDC_CHECK3,0); CheckDlgButton(IDC_CHECK4,0); return true; } void OnOK() { CString name, result; result+=”Name”; GetDlgItemText(IDC_EDIT1,name); result+=name; result+=”n”; result+=”AGE”; CString st; GetDlgItemText(IDC_EDIT2,st); result+=st; result+=”n”; result+=”YEAR”; int college=GetCheckedRadioButton(IDC_RADIO1, IDC_RADIO3); switch(college) { case IDC_RADIO1: result+=”I Year”; break; case IDC_RADIO2: result+=”II Year”; break; case IDC_RADIO3: result+=”III Year”; break; } result+=”n”; result+=”PASSED IN: ”; if(IsDlgButtonChecked(IDC_CHECK1)==1) result+=”Unix”; if(IsDlgButtonChecked(IDC_CHECK2)==1) result+=”VC++”; if(IsDlgButtonChecked(IDC_CHECK3)==1) result+=”OOAD”; if(IsDlgButtonChecked(IDC_CHECK4)==1) result+=”RMT”; MessageBox(result, “RESULT”); } void OnCancel() { CDialog::OnCancel(); 38
  • 39. MessageBox(“Cancelled”); } }; class mywin::public CFrameWnd { public: mywin() { Create(0,”MFC”,WS_OVERLAPPEDWINDOW, CRect(100,100,600,500),0, MAKEINTRESOURCE(IDR_MENU1); } void result() { mydialog d; d.DoModal(); } void end() { PostQuitMessage(0); } DECLARE_MESSAGE_MAP() }; BEGIN_MESSAGE_MAP(mywin, CFrameWnd) ON_COMMAND(101, result); ON_COMMAND(102,end); END_MESSAGE_MAP() Class myapp:public CWinApp { BOOL InitInstance() { mywin *p; p= new mywin(); m_pMainWnd=p; p->ShowWindow(1); return true; } }; myapp A; 39
  • 41. Ex.No: 12 Dynamic Controls Date : Aim: To write a VC++ program to implement the dynamic controls Logical Description: The program starts with object creation. After initializing the instance, the user created window is assigned as main window. Using Show window option project user created window. Using message mapping create dynamically controls such as label, edit box and button Algorithm: 1. Start the process 2. Initially control starts from object creation 3. Next it calls the myapp class which in turn calls the constructor 4. The constructor creates an Output:window 5. Create name, address, phone and password using WS_VISIBLE, WS_CHILD & SS_CENTREIMAGE. 6. Define respective message maps for the corresponding functions. 7. Execute the program 8. Stop the process Source Code: #include<afxwin.h> #include<ctype.h> #define EDIT_NUM 100 #define BUT_OK 103 class myedit:public CEdit { public: void OnChar(UINT nChar,UINT nRepCnt,UINT nFlags) { if(isdigit(nChar)) CEdit::OnChar(nChar,nRepCnt,nFlags); else ::MessageBeep(0); 41
  • 42. } DECLARE_MESSAGE_MAP() }; BEGIN_MESSAGE_MAP(myedit,CEdit) ON_WM_CHAR() END_MESSAGE_MAP() class mywin:public CFrameWnd { private: myedit edit_num; CStatic label; CButton okbut; public: mywin() { Create(NULL,"Edit box"); } int OnCreate(LPCREATESTRUCT lp) { RECT rect; rect.top=10; rect.left=10; rect.right=130; rect.bottom=30; label.Create("Enter numbers",WS_CHILD|WS_VISIBLE| WS_BORDER,rect,this); rect.top=10; rect.left=131; rect.right=250; rect.bottom=30; edit_num.Create(WS_CHILD|WS_VISIBLE| WS_BORDER,rect,this,EDIT_NUM); edit_num.LimitText(10); rect.top=40; rect.left=110; rect.right=150; rect.bottom=60; okbut.Create("&OK",WS_CHILD|WS_VISIBLE|WS_BORDER| BS_PUSHBUTTON,rect,this,BUT_OK); edit_num.SetFocus(); return 0; } void OnButOk() { char buff[25]; edit_num.GetWindowText(buff,25); 42
  • 43. MessageBox(buff,"Data retrieved"); } DECLARE_MESSAGE_MAP() }; BEGIN_MESSAGE_MAP(mywin,CFrameWnd) ON_COMMAND(BUT_OK,OnButOk) ON_WM_CREATE() END_MESSAGE_MAP() class myapp:public CWinApp { public: BOOL InitInstance() { mywin *p; p=new mywin(); m_pMainWnd=p; p->ShowWindow(SW_SHOWNORMAL); return true; } }; myapp A; Output: 43
  • 44. Ex.No: 13 SDI Serialization Date : Aim: To write a VC++ program to implement SDI Serialization Logical Description: Process of saving and restoring objects is called serialization. Implement serialization for SDI applications Algorithm: 1. Start the process 2. Create an object for myapp and invoke a method InitInstance( ) which calls mywin( ). 3. Write a method to write into a file: OnWrite( ) in mywin class. 4. Write a method to read from a file : OnRead ( ) in the class mywin. 5. Map these methods to the members created. 6. Stop the process Source Code: // sdiDoc.cpp : implementation of the CSdiDoc class #include "stdafx.h" #include "sdi.h" #include "sdiDoc.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CSdiDoc IMPLEMENT_DYNCREATE(CSdiDoc, CDocument) BEGIN_MESSAGE_MAP(CSdiDoc, CDocument) //{{AFX_MSG_MAP(CSdiDoc) 44
  • 45. // NOTE - the ClassWizard will add and remove mapping macros here. // DO NOT EDIT what you see in these blocks of generated code! //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CSdiDoc construction/destruction CSdiDoc::CSdiDoc() { // TODO: add one-time construction code here } CSdiDoc::~CSdiDoc() { } BOOL CSdiDoc::OnNewDocument() { if (!CDocument::OnNewDocument()) return FALSE; dx=50; dy=50; // TODO: add reinitialization code here // (SDI documents will reuse this document) return TRUE; } ///////////////////////////////////////////////////////////////////////////// // CSdiDoc serialization void CSdiDoc::Serialize(CArchive& ar) { if (ar.IsStoring()) { // TODO: add storing code here ar<<dx<<dy; //ar>>dx>>dy; } else { // TODO: add loading code here //ar<<dx<<dy; ar>>dx>>dy; } } ///////////////////////////////////////////////////////////////////////////// // CSdiDoc diagnostics #ifdef _DEBUG void CSdiDoc::AssertValid() const 45
  • 46. { CDocument::AssertValid(); } void CSdiDoc::Dump(CDumpContext& dc) const { CDocument::Dump(dc); } #endif //_DEBUG ///////////////////////////////////////////////////////////////////////////// // CSdiDoc commands Output: 46
  • 47. Ex.No: 14 MDI Serialization Date : Aim: To write a VC++ program to implement MDI serialization Logical Description: Process of saving and restoring objects is called serialization. Implement serialization for MDI applications Algorithm: 1. Start the process 2. Select MFC appwizard (Exe) and select multiple document in that. 3. Give next for further steps and finally click finish button 4. Create menu for read and write 5. For both read and write go to the class wizard, select command in that and write the required codings 6. The document file will be available in the local space where we have started. 7. Execute the program 8. Stop the process Source Code: // serializationmdiView.cpp : implementation of the CSerializationmdiView class #include "stdafx.h" #include "serializationmdi.h" #include "serializationmdiDoc.h" #include "serializationmdiView.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CSerializationmdiView 47
  • 48. IMPLEMENT_DYNCREATE(CSerializationmdiView, CView) BEGIN_MESSAGE_MAP(CSerializationmdiView, CView) //{{AFX_MSG_MAP(CSerializationmdiView) ON_COMMAND(ID_WRITE, OnWrite) ON_COMMAND(ID_READ, OnRead) //}}AFX_MSG_MAP // Standard printing commands ON_COMMAND(ID_FILE_PRINT, CView::OnFilePrint) ON_COMMAND(ID_FILE_PRINT_DIRECT, CView::OnFilePrint) ON_COMMAND(ID_FILE_PRINT_PREVIEW, CView::OnFilePrintPreview) END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CSerializationmdiView construction/destruction CSerializationmdiView::CSerializationmdiView() { // TODO: add construction code here } CSerializationmdiView::~CSerializationmdiView() { } BOOL CSerializationmdiView::PreCreateWindow(CREATESTRUCT& cs) { // TODO: Modify the Window class or styles here by modifying // the CREATESTRUCT cs return CView::PreCreateWindow(cs); } ///////////////////////////////////////////////////////////////////////////// // CSerializationmdiView drawing void CSerializationmdiView::OnDraw(CDC* pDC) { CSerializationmdiDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); // TODO: add draw code for native data here } ///////////////////////////////////////////////////////////////////////////// // CSerializationmdiView printing BOOL CSerializationmdiView::OnPreparePrinting(CPrintInfo* pInfo) { // default preparation return DoPreparePrinting(pInfo); } void CSerializationmdiView::OnBeginPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/) 48
  • 49. { // TODO: add extra initialization before printing } void CSerializationmdiView::OnEndPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/) { // TODO: add cleanup after printing } ///////////////////////////////////////////////////////////////////////////// // CSerializationmdiView diagnostics #ifdef _DEBUG void CSerializationmdiView::AssertValid() const { CView::AssertValid(); } void CSerializationmdiView::Dump(CDumpContext& dc) const { CView::Dump(dc); } CSerializationmdiDoc* CSerializationmdiView::GetDocument() // non-debug version is inline { ASSERT(m_pDocument- >IsKindOf(RUNTIME_CLASS(CSerializationmdiDoc))); return (CSerializationmdiDoc*)m_pDocument; } #endif //_DEBUG ///////////////////////////////////////////////////////////////////////////// // CSerializationmdiView message handlers void CSerializationmdiView::OnWrite() { CFile *f; f = new CFile; f->Open("D:mdi.txt", CFile::modeCreate|CFile ::modeWrite); f->Write("Welcome to VC++", 15); f->Close(); MessageBox("Data Written", "File Write"); } void CSerializationmdiView::OnRead() { char x[100]; CFile *f; 49
  • 50. f = new CFile; f->Open("D:mdi.txt", CFile::modeRead); DWORD size = f->GetLength(); f->Read(x, size); f->Close(); CClientDC dc(this); dc.TextOut(50,50, x, size); } Output: 50
  • 51. Ex.No: 15 ODBC Connectivity Date : Aim: To Write a VC++ program that implements database connectivity Logical Description: Implementing ODBC connectivity for a SDI application Algorithm: 1. Create a database and table in MSAccess. Goto MSACCESS,  File->New->Blank database->Give database name(Students details)  Inside that database create a table named stud with fields Roll no and Name.  Enter details for some five records ,save and exit. 2. Creating a DSN  Goto Control Panel->click Data sources(ODBC)  Click user DSN tab  Click the Add button  Double click Driver Do Microsoft Access(*.mdb)  Give data source name as DSN1  Select database(the location where u have stored ur students details database)  Click ok  Now the DSN is created. 3. Run Appwizard(EXE) to create a SDI project named stud.  Select Header files only option in step 2.  Set CScrollView as class type in step 6. 4. Use class wizard  Choose Add class->New->give class name(CStudSet) and set base class name as CRecordSet.  Click ok,it will show a Database options dialog box.  In that select the DSN name and click Recordset type as dynaset,click ok. 51
  • 52.  It will ask u to select the table,select the table name stud,click ok. 5. Add the member variable to the class CstudDoc CStudSet m_studSet; 6. Edit the studDoc.cpp file Add the line #include “studSet.h” before the line #include “studDoc.h”. 7. Add the following private data member to the CstudView class. CStudSet* m_pSet; 8. Edit the OnDraw and OnInitialUpdate functions in studView.cpp. void CStudView::OnDraw(CDC* pDC) { TEXTMETRIC tm; pDC->GetTextMetrics(&tm); int nLineHeight=tm.tmHeight+tm.tmExternalLeading; CPoint pText(0,0); int y=0; CString str; if(m_pSet->IsBOF()) return; m_pSet->MoveFirst(); while(!m_pSet->IsEOF()){ str.Format("%ld",m_pSet->m_Roll); pDC->TextOut(pText.x,pText.y,str); pDC->TextOut(pText.x+1000,pText.y,m_pSet->m_Name); m_pSet->MoveNext(); pText.y-=nLineHeight; } } void CStudView::OnInitialUpdate() { CScrollView::OnInitialUpdate(); CSize sizeTotal(8000,10500); // TODO: calculate the total size of this view SetScrollSizes(MM_HIENGLISH, sizeTotal); m_pSet=&GetDocument()->m_studSet; if(m_pSet->IsOpen()) m_pSet->Close(); m_pSet->Open(); } 52
  • 53. Add the #include “studSet.h” before the line #include “studDoc.h” 9. Edit the stud.cpp file Add #include “studSet.h” before the line #include “studDoc.h” 10. Build and run the application. Output: 53
  • 54. Ex.No: 16 Dynamic Link Library Date : Aim: To calculate the simple interest using Dynamic Link Library (DLL). Logical Description: Dynamic Link Libraries(DLL):  A DLL is a collection of small programs, any of which can be called when needed by a large program that is running in the computer  The advantage of DLL files is that, because they do not get loaded into RAM together with the main program, space is saved in RAM. When and if a DLL file is needed, then it is loaded and run.  Examples As long as a user of MsWord is editing a document, the printer DLL file does not need to be loaded into RAM.  If the user decides to print the document, then the word application causes the printer DLL file to be loaded and run.  A DLL file is often given a “.DLL” file name .DLL files are dynamically linked with the program that uses them during program execution rather then being complied with the main program. Algorithm: 1. Create a dynamic link library 2. Create the Client Program 3. Go to project ->settings->link tab->object/library modules->C:vc++dmDebug dm.lib(Type the above said path) 4. Now copy the .DLL file which has been created in the C:vc++dmDebug to the client program in the path C:vc++dc. 5. Compile the Client Application and run the application. Click on the calculate button to view the result in the last edit control. Source Code: 54
  • 55. MYClass.cpp Float CMYClass :: interest(float p, float n, float r) { return(p*n*r/100); } dcDlg.h #include ”c:vc++dmMyClass.h” public: CMyClass objclass; Include the following lines in dcDlg.cpp void dcDlg::OnButton1() { UpdateData(true) m_res=objclass.interest(m_p,m_n,m_r); UpdateData(false); } void dcDlg::On Button2() { PostQuitMessage(0); } Output: 55
  • 56. Ex.No: 17 Document / View Architecture Date : Aim: To write a VC++ program to implements Document / View architecture Logical Description: Implementing Document / View Architecture for SDI applications and creating some drawing objects Algorithm: 1. Start the process 2. Create an object for myapp calss. Using he object allocate memory to the mywin class and call the constructor. 3. mywin class inherits the properties of CFrameWnd class 4. Draw some objects using message handler 5. Execute the program 6. Stop the process Source Code: sdisquaresDoc.h header file //Implementation public: void SetSquare(int i,int j,COLORREF color); COLORREF GetSquare(int i,int j); COLORREF GetCurrentColor(); Virtual ~CsdisquaresDoc(); //Generated messagemap functions prortected: COLORREF m_clrCurrentColor; COLORREF m_clrGrid[4][4]; //{{AFX_MSG(CsdisquaresDoc) afx_msg void OnColorRed(); afx_msg void OnColorGreen(); afx_msg void OnColorBlue(); afx_msg void OnColorWhite(); 56
  • 57. //}}AFX_MSG sdisquaresDoc.cpp BEGIN_MESSAGE_MAP( ) //{{AFX_MSG_MAP( ) ON_COMMAND(ID_COLOR_RED,OnColorRed) ON_COMMAND(ID_COLOR_BLUE,OnColorBlue) ON_COMMAND(ID_COLOR_GREEN,OnColorGreen) ON_COMMAND(ID_COLOR_WHITE,OnColorWhite) //}}AFX_MSG_MAP END_MESSAGE_MAP() BOOL CsdisquaresDoc::OnNewDocument() { if(!CDocument::OnNewDocument()) return FALSE; for(int i=0;i<4;i++) for(j=0;j<4;j++) m_clrGrid[i][j]=RGB(255,255,255); m_clrCurrentColor=RGB(255,0,0); return TRUE; } void CsdisquaresDoc::Serialize(CArchive &ar) { if(ar.IsStoring()) { for(int i=0;i<4;i++) for(int j=0;j<4;j++) ar<<m_clrGrid[i][j]; ar<<m_clrCurrentColor; } else { for(int i=0;i<4;i++) for(int j=0;j<4;j++) ar>>m_clrGrid[i][j]; ar>>m_clrCurrentColor; } } //CsdisquaresDoc commands COLORREF Csdisquares::GetCurrentColor() 57
  • 58. { return m_clrCurrentColor; } COLORREF csdisquaresDoc::GetSquare(int I,int j) { ASSERT(i>=0&&i<=3&&j>=0&&j<=3); Return m_clrGrid[i][j]; } void CsdisquaresDoc::SetSquare(int i,int j,COLORREF color) { ASSERT(i>=0&&i<=3&&j>=0&&j<=3); M_clrGrid[i][j]=color; SetModifiedFlag(TRUE); UpdateAllViews(NULL); } void CsdisquaresDoc::OnColorRed() { m_clrCurrentColor=RGB(255,0,0); } void CsdisquaresDoc::OnColorGreen() { m_clrCurrentColor=RGB(0,255,0); } void CsdisquaresDoc::OnColorBlue() { m_clrCurrentColor=RGB(0,0,255); } void CsdisquaresDoc::OnColorWhite() { m_clrCurrentColor=RGB(255,255,255); } sdisquaresview.h header file //{{AFX_MSG( ) afx_msg void OnLButtonDown(UINT nFlags,CPoint point); //}}AFX_MSG sdisquaresview.cpp BEGIN_MESSAGE_MAP( ) //{{AFX_MSG( ) ON_WM_LBUTTONDOWN() //}}AFX_MSG_MAP 58
  • 59. void Csdisquaresview::OnDraw(CDC* pDC) { CsdisquaresDoc* pDoc=GetDocument(); ASSERT_VALID(pDoc); pDC->SetMapMode(MM_LOENGLISH); //Draw 16 squares for(int i=0;i<4;i++){ for(int j=0;j<4;j++){ COLORREF color=pDoc->GetSquare(i,j); CBrush brush(color); int x1=(j*100)+50; int y1=(i*-100)-50; int x2=x1+100; int y2=y1-100; CRect rect(x1,y1,x2,y2); pDC->FillRect(rect,&Brush); } } //Draw grid lines around them for(int x=50;x<=450;x+=100){ pDC->MoveTo(x,-50); pDC->LineTo(x,-450); } for(int y=-50;y>=-450;y-=100){ pDC->MoveTo(50,y); pDC->LineTo(450,y); } } void Csdisquaresview::OnLButtonDown(UINT nFlags,CPoint point) { Cview::OnLButtonDown(nFlags,point); CClientDC dc(this); dc.SetMapMode(MM_LOENGLISH); CPoint pos=point; dc.DPtoLP(&pos); //if the square was clicked,set its color to the current color if(pos.x>=50&&pos.x<=450&&pos.y<=-50&&pos.y>=-450){ int i=(-pos.y-50)/100; int j=(pos.x-50)/100; CsdisquaresDoc* pDoc=GetDocument(); COLORREF clrCurrentColor=pDoc->GetCurrentColor(); pDoc->SetSquare(i,j,clrCurrentColor); } } 59