vc++ programs

Upload: stalinbalusamy

Post on 30-Oct-2015

55 views

Category:

Documents


0 download

TRANSCRIPT

Aim:

.

VISUALC++ PROGRAMMING

Ex.No: 1Window 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 Process2. Create an object for an class which inherits CWinApp3. The object access InitInstance() function4. Create a pointer object for the class which inherits CFrameWindow by allocating the memory to the object5. Show the created window using SW_SHOWNORMAL6. Stop the process Source Code:

#includeclass 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 threadp->ShowWindow(SW_SHOWNORMAL);return TRUE;}};

myapp A;

Output:

Ex.No: 2Graphical 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 Process2. 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 constructor4. Inside message map write the code for GDI objects like pen & brush .5. Show the created window using SW_SHOWNORMAL6. Stop the process

Source Code:

#include class mywnd : public CFrameWnd{public: mywnd() { Create(0,"MFC"); }DECLARE_MESSAGE_MAP()void OnLButtonDown(UINT f,CPoint p){ CPen pen; CBrush brush; 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;

Output:

Ex.No: 3Modeless 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 process2. Create a dialog box using IDD_DIALOG1 and add the items in it3. 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 instance5. Call the create method (creation of instance) on the event RButtonDown6. Stop the process

Source Code:

#include#include#include "resource.h"

class mydlg:public CDialog{

public:mydlg():CDialog(){

}public:BOOL OnInitDialog(){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{public:BOOL InitInstance(){mywin *p;p=new mywin();m_pMainWnd=p;p->ShowWindow(SW_SHOWNORMAL);return true;}}; myapp A;

Output:

Ex.No: 4Single 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 frameworks 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"

#include "sdiDoc.h"#include "sdiView.h"

#ifdef _DEBUG#define new DEBUG_NEW#undef THIS_FILEstatic 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 commandsON_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);}

/////////////////////////////////////////////////////////////////////////////// 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 preparationreturn 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 _DEBUGvoid CSdiView::AssertValid() const{CView::AssertValid();}

void CSdiView::Dump(CDumpContext& dc) const{CView::Dump(dc);}

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:

Ex.No: 5Multiple 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 frameworks 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"#include "mdiView.h"

#ifdef _DEBUG#define new DEBUG_NEW#undef THIS_FILEstatic 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 commandsON_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

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 preparationreturn 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 _DEBUGvoid CMdiView::AssertValid() const{CView::AssertValid();}

void CMdiView::Dump(CDumpContext& dc) const{CView::Dump(dc);}

CMdiDoc* CMdiView::GetDocument() // non-debug version is inline{ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CMdiDoc)));return (CMdiDoc*)m_pDocument;}#endif //_DEBUG

/////////////////////////////////////////////////////////////////////////////// CMdiView message handlers

Output:

Ex.No: 6Dynamic 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 process2. Initially control starts from object creation3. Next it calls the myapp class which in turn calls the constructor4. The constructor creates an Output:window5. 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#include#define EDIT_NUM 100#define BUT_OK 103class myedit:public CEdit{public:void OnChar(UINT nChar,UINT nRepCnt,UINT nFlags){if(isdigit(nChar))CEdit::OnChar(nChar,nRepCnt,nFlags);else::MessageBeep(0);}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);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:

Ex.No: 7SDI 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 process2. 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_FILEstatic char THIS_FILE[] = __FILE__;#endif/////////////////////////////////////////////////////////////////////////////// CSdiDocIMPLEMENT_DYNCREATE(CSdiDoc, CDocument)BEGIN_MESSAGE_MAP(CSdiDoc, CDocument)//{{AFX_MSG_MAP(CSdiDoc)// NOTE - the ClassWizard will add and remove mapping macros here.// DO NOT EDIT what you see in these blocks of generated code!//}}AFX_MSG_MAPEND_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 serializationvoid CSdiDoc::Serialize(CArchive& ar){if (ar.IsStoring()){// TODO: add storing code hereardy;}else{// TODO: add loading code here//ardy;}}/////////////////////////////////////////////////////////////////////////////// CSdiDoc diagnostics#ifdef _DEBUGvoid CSdiDoc::AssertValid() const{CDocument::AssertValid();}void CSdiDoc::Dump(CDumpContext& dc) const{CDocument::Dump(dc);}#endif //_DEBUG/////////////////////////////////////////////////////////////////////////////// CSdiDoc commands

Output:

Ex.No: 8MDI 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 process2. Select MFC appwizard (Exe) and select multiple document in that.3. Give next for further steps and finally click finish button4. 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 codings6. 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_FILEstatic char THIS_FILE[] = __FILE__;#endif/////////////////////////////////////////////////////////////////////////////// CSerializationmdiViewIMPLEMENT_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 commandsON_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/destructionCSerializationmdiView::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 drawingvoid CSerializationmdiView::OnDraw(CDC* pDC){CSerializationmdiDoc* pDoc = GetDocument();ASSERT_VALID(pDoc);// TODO: add draw code for native data here}/////////////////////////////////////////////////////////////////////////////// CSerializationmdiView printingBOOL CSerializationmdiView::OnPreparePrinting(CPrintInfo* pInfo){// default preparationreturn DoPreparePrinting(pInfo);}

void CSerializationmdiView::OnBeginPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/){// TODO: add extra initialization before printing}

void CSerializationmdiView::OnEndPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/){// TODO: add cleanup after printing}

/////////////////////////////////////////////////////////////////////////////// CSerializationmdiView diagnostics#ifdef _DEBUGvoid 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 handlersvoid 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;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:

Ex.No: 9Slider Control

Date :

Aim:To write a Visual C++ program for creating a Slider Control 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:

7. Start the Process8. Create an object for an class which inherits CWinApp9. The object access InitInstance() function10. Create a pointer object for the class which inherits CFrameWindow by allocating the memory to the object11. Show the created window using SW_SHOWNORMAL12. Stop the process Source Code: #include#includeclass myframe:public CFrameWnd{private:CSliderCtrl sli;CButton gr;public:myframe(){CString mywindowclass;mywindowclass=AfxRegisterWndClass(CS_VREDRAW|CS_HREDRAW,0,(HBRUSH)::GetStockObject(LTGRAY_BRUSH),0);Create(mywindowclass,"Slider Control");}int OnCreate(LPCREATESTRUCT I){CFrameWnd::OnCreate(I);gr.Create("SLIDER DISPLAY",WS_CHILD|WS_VISIBLE|BS_GROUPBOX,CRect(30,30,310,100),this,1);sli.Create(WS_CHILD|WS_VISIBLE|TBS_HORZ|TBS_AUTOTICKS|TBS_BOTTOM|TBS_ENABLESELRANGE,CRect(35,50,305,90),this,2);sli.SetRange(0,8);sli.SetPos(2);sli.SetSelection(0,2);sli.SetPageSize(3);return 0;}void OnHScroll(UINT code,UINT pos,CScrollBar *scroll){switch(code){case TB_LINEUP:

case TB_LINEDOWN:case TB_PAGEUP:case TB_PAGEDOWN:case TB_TOP:case TB_BOTTOM:

pos=sli.GetPos();sli.SetSelection(0,pos);sli.SetTic(pos);break;case TB_THUMBPOSITION:sli.SetSelection(0,pos);sli.SetTic(pos);break;case TB_THUMBTRACK:sli.SetSelection(0,pos);sli.SetTic(pos);break;}}DECLARE_MESSAGE_MAP()};BEGIN_MESSAGE_MAP(myframe,CFrameWnd)ON_WM_CREATE()ON_WM_HSCROLL()END_MESSAGE_MAP()class myapp:public CWinApp{public:int InitInstance(){myframe *p;p=new myframe;p->ShowWindow(3);m_pMainWnd=p;return 1;}};myapp a;

Output:

Ex.No: 10Tree View Creation

Date :

Aim:To write a Visual C++ program for creating a Tree View Control 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:

13. Start the Process14. Create an object for an class which inherits CWinApp15. The object access InitInstance() function16. Create a pointer object for the class which inherits CFrameWindow by allocating the memory to the object17. Show the created window using SW_SHOWNORMAL18. Stop the process Source Code: #include#includeclass myframe:public CFrameWnd{private:CTreeCtrl tree;public:myframe(){Create(0,"Tree view control");}int OnCreate(LPCREATESTRUCT I){HTREEITEM lang,opersys,c,cpp,java;CFrameWnd::OnCreate(I);tree.Create(WS_CHILD|WS_VISIBLE|WS_BORDER|TVS_HASLINES|TVS_LINESATROOT|TVS_HASBUTTONS|TVS_SHOWSELALWAYS,CRect(30,30,300,350),this,1);lang=tree.InsertItem("Computer languages",TVI_ROOT,TVI_SORT);c=tree.InsertItem("C",lang,TVI_SORT);tree.InsertItem("TC",c);tree.InsertItem("QC",c);tree.InsertItem("MSC",c);cpp=tree.InsertItem("c++",lang,TVI_SORT);tree.InsertItem("VC++",cpp);tree.InsertItem("Borland c++",cpp);java=tree.InsertItem("java",lang,TVI_SORT);tree.InsertItem("VJ++",java);tree.InsertItem("Symantec cafe",java);tree.InsertItem("Sun JDK",java);opersys=tree.InsertItem("operating systems",TVI_ROOT,TVI_SORT);tree.InsertItem("win 3.1",opersys);tree.InsertItem("win 95",opersys);tree.InsertItem("win NT",opersys);return 0;}int OnNotify(WPARAM w,LPARAM I,LRESULT *r){HTREEITEM h;CString str;CWnd::OnNotify(w,I,r);NM_TREEVIEW *p=(NM_TREEVIEW *)I;if(p->hdr.code==TVN_SELCHANGED){h=tree.GetSelectedItem();str=tree.GetItemText(h);MessageBox(str,"you have selected");}return 1;}DECLARE_MESSAGE_MAP()};BEGIN_MESSAGE_MAP(myframe,CFrameWnd)ON_WM_CREATE()END_MESSAGE_MAP()class myapp:public CWinApp{public:int InitInstance(){myframe *p;p=new myframe;p->ShowWindow(3);m_pMainWnd=p;return 1;}};myapp a;

Output:

Ex. No: 11PROGRESS CONTROL CREATION

Date :

Aim:To write a Visual C++ program for creating a Progress Control Creation 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 Process2.Create an object for an class which inherits CWinApp3.The object access InitInstance() function4.Create a pointer object for the class which inherits CFrameWindow by allocating the memory to the object5.Show the created window using SW_SHOWNORMAL6.Stop the process

Source Code:

#include#include#include "resource.h"class sortdialog:public CDialog{private:CString fname;Public:sortdialog(int n):CDialog(n){fname="Enter file to be sorted";}void DoDtaExchange(CDataExchange *p){DDX_Text(p,IDC_EDIT1,fname);}void OnOk(){CString str[100],temp;CStdioFile fp;CProgressCtrl *c;UpdateData(TRUE);c=(CProgressCtrl*)GetDlgItem(IDC_PROGRESS1);c->SetStep(5);if(fp.Open(fname,CFile::modeReadWrite)){int count=0;fp.SeekToBegin();while(fp.ReadString (str[count])!=NULL)count++;for(int j=0;jStepIt();Sleep(100);}fp.SeekToBegin();for(int i=0;iOpen("dillo.avi");c->Play(0,-1,-1);if(fs.Open(source,CFile::modeRead)==0){MessageBox("cannot open source file","file error");return;}if(fs.Open(target,CFile::modeCreate|CFile::modeWrite)==0){MessageBox("cannot open source file","file error");return;}while(fs.ReadString(str,199)!=NULL){ft.WriteString(str);Sleep(100);}fs.Close();ft.Close();

c->Stop();c->Close();

EndDialog(1);}};class myframe:public CFrameWnd{public:myframe(){Create(0,"progress bar and animationcontrol",WS_OVERLAPPEDWINDOW,rectDefault,0);}void sort(){sortdialog *d;d= new sortdialog(IDD_DIALOG1);d->DoModal();}void copy(){copydialog *d;d=new copydialog(IDD_DIALOG2);d->DoModal();}DECLARE_MESSAGE_MAP()};BEGIN_MESSAGE_MAP(myframe,CFrameWnd)ON_COMMAND(101,sort)ON_COMMAND(102,copy)END_MESSAGE_MAP()class myapp:public CWinApp{public:int InitInstance(){myframe *p;p=new myframe;p->ShowWindow(3);m_pMainWnd=p;return 1;} };myapp a;

Output:

Ex.No: 12Splitter View

Date :

Aim:To write a Visual C++ program for creating a Splitter View Control 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 Process2.Create an object for an class which inherits CWinApp3. The object access InitInstance () function4. Create a pointer object for the class which inherits CFrameWindow by allocating the memory to the object5. Show the created window using SW_SHOWNORMAL6. Stop the process

Source Code:

// SplitterDoc.cpp : implementation of the CSplitterDoc class//#include "stdafx.h"#include "Splitter.h"#include "SplitterDoc.h"#ifdef _DEBUG#define new DEBUG_NEW#undef THIS_FILEstatic char THIS_FILE[] = __FILE__;#endif/////////////////////////////////////////////////////////////////////////////// CSplitterDocIMPLEMENT_DYNCREATE(CSplitterDoc, CDocument)BEGIN_MESSAGE_MAP(CSplitterDoc, CDocument)//{{AFX_MSG_MAP(CSplitterDoc)// NOTE - the ClassWizard will add and remove mapping macros here.// DO NOT EDIT what you see in these blocks of generated code!//}}AFX_MSG_MAPEND_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////// CSplitterDoc construction/destructionCSplitterDoc::CSplitterDoc(){// TODO: add one-time construction code here

}CSplitterDoc::~CSplitterDoc(){}

BOOL CSplitterDoc::OnNewDocument(){if (!CDocument::OnNewDocument())return FALSE;

// TODO: add reinitialization code here// (SDI documents will reuse this document)

return TRUE;}/////////////////////////////////////////////////////////////////////////////// CSplitterDoc serializationvoid CSplitterDoc::Serialize(CArchive& ar){// CEditView contains an edit control which handles all serialization((CEditView*)m_viewList.GetHead())->SerializeRaw(ar);}/////////////////////////////////////////////////////////////////////////////// CSplitterDoc diagnostics#ifdef _DEBUGvoid CSplitterDoc::AssertValid() const{CDocument::AssertValid();}void CSplitterDoc::Dump(CDumpContext& dc) const{CDocument::Dump(dc);}#endif //_DEBUG/////////////////////////////////////////////////////////////////////////////// CSplitterDoc commands

Output:

Ex. No. 13Creating DLL and Using itAim:

To write a VC++ program to develop DLL and export the function using MFC (.dll) and use the same function in the client program using MFC (.exe).

Logical Description:

DLL is a file on disk with a DLL extension consisting of global data, compiled functions, and resources that becomes part of our process. It is compiled to load at a preferred base address, and if there is no conflict with other DLLs, the file gets mapped to the same virtual address in our process. The DLL consists of exported function, and the client program imports those exported functions. Windows matches up the imports and exports when it loads the DLL.

Classes are build-time modular DLLs are runtime modular

Client programs can load and link our DLL very quickly when they run.

This program is to create SayHello( ) in the DLL and exported this function to any client program to use it. Also this DLL is included in the client program to use the SayHello( ).

Steps to build the MyDll and TestDll application:

DLL Server MyDll.dsw

1. Run VC++ MFC AppWizard to create (.dll)..\MyDll

2. Select Regular DLL using Shared MFC DLL and click finish.

3. Goto Class View and right click the MyDll class and choose New Class.

4. Now choose the class type to be the Generic Class and type the class name as CMyClass then click OK.

5. Then add member function to the CMyClass by right clicking and type,

a. function type as CString b. function name as SayHello(CString strName); c. access type is public

6. Add the function definition in MyClass.cpp

CString CMyClass:: SayHello(CString strName){ return Hello + strName;}

7. To call the DLL function from an external application we have to prefix the function with the signature in MyClass.h with _declspec(dllexport). Add the following boldface code to the following statements in MyClass.h file,public:

_declspec(dllexport) CString SayHello(CSTring strName);_declspec(dllexport) CMyClass();_declspec(dllexport) virtual ~CMyClass();

8. Compile the code without executing.

DLL Client TestDll.dsw

1. Run the VC++ MFC AppWizard(.exe) to develop a dialog based application ..\Testdll.dsw

2. The resource editor will be enabled once finishing the project and add one static control, one edit control and one button control.

3. Add the id for the edit control IDC_NAME and add the member variable as m_sName and type as CString by using the class wizard.

4. Use the class wizard to map the message OnOk function for IDOK in the TestDllDlg class.

5. Now edit the code on TestDllDlg.cpp

Void CTestDllDlg::OnOk(){CMyClass objMyClass;UpdateData(true);CString str = objMyClass.SayHello(m_sName);AfxMessageBox(str);}

6. Now add the entire path of the MyDll server header file in TestDllDlg.h

#include E:\Exercise\MyDll\MyClass.h

7. Click the project menu and select the settings and click on the link tab and type the entire path of the MyDll.lib file in the Object/Library Modules text boxes as,

E:\Exercise\MyDll\Debug\MyDll.lib

8. Now copy the MyDll.dll in the MyDll Debug folder into the TestDll folder.

9. Build the project and execute it.

Output:

EX NO.14 Data Access through ODBC

Aim:

To write a VC++ program to access the Student database through MFC ODBC.

Logical Description:

The program isolates the database access code from user interface code so that we can see how to add ODBC database capability to any MFC application. Here ClassWizard to generate a CRecordset class, but won't be using the CRecordView class that AppWizard generates when you ask for a database view application. This application is fairly simple. It displays the rows from the student database table in a scrolling view. The student table is part of the Student NameList database that's included with Visual C++.

Steps for building the Student application:

1. Create the database stud.mdb using MS Access.

2. Run the ODBC Data Source Administrator to install the Student Registration data source. a. Click the ODBC icon in the Windows Control Panel. b. Click the Drivers tab to see whether the Microsoft Access driver is available. c. Click the Add button (the Add button is on the User DSN tab), d. choose Microsoft Access Driver in the Add Data Source dialog box (select the Microsoft Access Driver in the Create New Data Source dialog box and click the Finish button), e. And fill in the ODBC Microsoft Access Setup dialog box.

f. Set the database to point to stud.mdb using the Select button. Finally, click the OK button. 3. Run AppWizard to produce \vcpp\Student.

a. Specify an SDI application (Step 1 dialog box).b. Select the Header Files Only option from the AppWizard Step 2 dialog box, as shown here. c. Select CScrollView as the view's class type (Step 6 dialog box).

4. Use ClassWizard to create the CStudentSet recordset class.

a. Choose New from the Add Class menu, and then fill in the New Class dialog box as shown here.

5. Select the Student Registration database's Student table for the CStudentSet class.a. When you click the OK button in the New Class dialog box, ClassWizard displays the Database Options dialog box. b. Select the Student Registration data source, and select the Dynaset option as shown here.

c. After you select the data source, ClassWizard prompts you to select a table. Select Student, as shown here.

6. Examine the data members that ClassWizard generates.

a. Click on the Member Variables tab for the newly generated CStudentSet class. b. ClassWizard should have generated data members based on student column names. 7. Declare an embedded recordset object in StudentDoc.h. a. Add the following public data member in the CStudentDoc class declaration: CStudentSet m_StudentSet;8. Edit the StudentDoc.cpp file. Add the line #include "StudentSet.h"just before the line #include "StudentDoc.h"9. Declare a recordset pointer in StudentView.h. a. Add the following private data member in the CStudentView class declaration: CStudentSet* m_pSet;10. Edit the OnDraw and OnInitialUpdate functions in StudentView.cpp. a. Add the following boldface code: void CStudentView::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()) { // detects empty recordset return; } m_pSet->MoveFirst(); // fails if recordset is empty while (!m_pSet->IsEOF()) { str.Format("%ld", m_pSet->m_RegNo); 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 CStudentView::OnInitialUpdate() { CScrollView::OnInitialUpdate(); CSize sizeTotal(8000, 10500);

SetScrollSizes(MM_HIENGLISH, sizeTotal);

m_pSet = &GetDocument()->m_StudentSet; // Remember that documents/views are reused in SDI applications! if (m_pSet->IsOpen()) { m_pSet->Close(); } m_pSet->Open();} b. Also in StudentView.cpp, add the line #include "StudentSet.h"just before the line #include "StudentDoc.h"11. Edit the Student.cpp file. Add the line #include "StudentSet.h"just before the line #include "StudentDoc.h"

12. Build and test the Student application.

ExNo: 15ActiveX Control Dialog Container

Aim:

To write a VC++ program to build an application that uses a Calendar control in a dialog using activeX.

Logical Description:

This project is to generate the calendar control in a dialog using ActiveX. An ActiveX control is a software module that plugs into your C++ program the same way a Windows control does. ActiveX Controls methods are like functions. A method has a symbolic name, a set of parameters, and a return value. The MSCal.ocx control is a popular Microsoft ActiveX Calendar control that's probably already installed and registered on your computer.

MFC and ClassWizard support ActiveX controls both in dialogs and as "child windows." Open the dialog, enter a date in the three edit controls, and then click the Select Date button. Click the Next Week button. Try moving the selected date directly to a new month, and observe the message box that is triggered by the NewMonth event. Watch for the final date in another message box when you click OK. Press the F1 key for help on the Calendar control.

Steps for building the calendar application: 1. Verify that the Calendar control is registered. If the control does not appear in the Visual C++ Gallery's Registered ActiveX Controls page, copy the files MSCal.ocx, MSCal.hlp, and MSCal.cnt to your system directory and register the control by running the REGCOMP program. 2. Run AppWizard to produce \vcpp32\ ActiveX. a. Select Single Document in Step 1b. In step3, make sure the ActiveX Controls option is selected.c. Deselect Printing and Print Preview in step 4 of 6. d. In the AppWizard Step 3 dialog, make sure the ActiveX Controls option is selected.3. Install the Calendar control in the Calendar project.

a. Choose Add To Project from Visual C++'s Project menu, and then choose Components And Controls. b. Choose Registered ActiveX Controls, and then choose Calendar Control 8.0.c. ClassWizard generates two classes in the ActiveX directory, as shown here.

4. Edit the Calendar control class to handle help messages. a. Add Calendar.cpp to the following message map code: BEGIN_MESSAGE_MAP(CCalendar, CWnd) ON_WM_HELPINFO()END_MESSAGE_MAP()b. In the same file, add the OnHelpInfo function: BOOL CCalendar::OnHelpInfo(HELPINFO* pHelpInfo) { // Edit the following string for your system ::WinHelp(GetSafeHwnd(), "c:\\winnt\\system32\\mscal.hlp",HELP_FINDER, 0); return FALSE;}c. In Calendar.h, add the function prototype and declare the message map: protected: afx_msg BOOL OnHelpInfo(HELPINFO* pHelpInfo); DECLARE_MESSAGE_MAP()The OnHelpInfo function is called if the user presses the F1 key when the Calendar control has the input focus. We have to add the message map code by hand because ClassWizard doesn't modify generated ActiveX classes.5. Use the dialog editor to create a new dialog resource. a. Choose Resource from Visual C++'s Insert menu, and then choose Dialog. b. The dialog editor assigns the ID IDD_DIALOG1 to the new dialog. c. Next change the ID to IDD_ACTIVEXDIALOG, change the dialog caption to ActiveX Dialog, and set the dialog's Context Help property (on the More Styles page). d. Accept the default OK and Cancel buttons with the IDs IDOK and IDCANCEL, and then add the other controls. e. Then add the other controls as shown below:

f. Make the Select Date button as the default button. g. Drag the Calendar control from the control palette. h. Then set an appropriate tab order. i. Assign control IDs as shown in the following table. ControlID

Calendar controlIDC_CALENDAR1

Select Date buttonIDC_SELECTDATE

Edit controlIDC_DAY

Edit controlIDC_MONTH

Edit controlIDC_YEAR

Next Week buttonIDC_NEXTWEEK

6. Use ClassWizard to create the CActiveXDialog class. a. If you run ClassWizard directly from the dialog editor window, it will know that you want to create a CDialog-derived class based on the IDD_ACTIVEXDIALOG template. b. Simply accept the default options, and name the class CActiveXDialog. c. Click on the ClassWizard Message Maps tab, and then add the message handler functions shown in the table below. d. To add a message handler function, click on an object ID, click on a message, and click the Add Function button. e. If the Add Member Function dialog box appears, type the function name and click the OK button. Object IDMessageMember Function

CActiveXDialogWM_INITDIALOGOnInitDialog (virtual function)

IDC_CALENDAR1NewMonth (event)OnNewMonthCalendar1

IDC_SELECTDATEBN_CLICKEDOnSelectDate

IDC_NEXTWEEKBN_CLICKEDOnNextWeek

IDOKBN_CLICKEDOnOK (virtual function)

7. Use ClassWizard to add data members to the CActiveXDialog class. a. Click on the Member Variables tab, and then add the data members as shown in the illustration below.

b. You might think that the ClassWizard ActiveX Events tab is for mapping ActiveX control events in a container. c. That's not true: it's for ActiveX control developers who are defining events for a control. 8. Edit the CActiveXDialog class. a. Add the m_varValue and m_BackColor data members.b. Edit the code for the five handler functions OnInitDialog, nNewMonthCalendar1, OnSelectDate, OnNextWeek, and OnOK. 9. Add the following boldface code in the ACTIVEXDIALOG.HPublic:COleVariant m_varValue; unsigned long m_BackColor;Note: declare these 2 variables at the end of the Dialog Data section.

10. Edit the ACTIVEXDIALOG.CPPa. Add the following boldface code.CActiveXDialog::CActiveXDialog(CWnd* pParent /*=NULL*/) : CDialog(CActiveXDialog::IDD, pParent){ // {{AFX_DATA_INIT (CActiveXDialog) m_sDay = 0; m_sMonth = 0; m_sYear = 0; //}}AFX_DATA_INIT m_BackColor = 0x8000000F;}

void CActiveXDialog::DoDataExchange(CDataExchange* pDX){ CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CActiveXDialog) DDX_Control(pDX, IDC_CALENDAR1, m_calendar); DDX_Text(pDX, IDC_DAY, m_sDay); DDX_Text(pDX, IDC_MONTH, m_sMonth); DDX_Text(pDX, IDC_YEAR, m_sYear); //}}AFX_DATA_MAP DDX_OCColor(pDX, IDC_CALENDAR1, DISPID_BACKCOLOR, m_BackColor);}BOOL CActiveXDialog::OnInitDialog() { CDialog::OnInitDialog(); m_calendar.SetValue(m_varValue); // no DDX for VARIANTs return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE

}void CActiveXDialog::OnNewMonthCalendar1() {AfxMessageBox("EVENT: CActiveXDialog::OnNewMonthCalendar1");}

void CActiveXDialog::OnSelectDate() { CDataExchange dx(this, TRUE); DDX_Text(&dx, IDC_DAY, m_sDay); DDX_Text(&dx, IDC_MONTH, m_sMonth); DDX_Text(&dx, IDC_YEAR, m_sYear); m_calendar.SetDay(m_sDay); m_calendar.SetMonth(m_sMonth); m_calendar.SetYear(m_sYear);}void CActiveXDialog::OnNextWeek() { m_calendar.NextWeek(); }

void CActiveXDialog::OnOK() { CDialog::OnOK(); m_varValue = m_calendar.GetValue(); // no DDX for VARIANTs}11. The OnSelectDate function is called when the user clicks the Select Date button. The function gets the day, month, and year values from the three edit controls and transfers them to the control's properties. ClassWizard can't add DDX code for the BackColor property, so you must add it by hand. In addition, there's no DDX code for VARIANT types, so you must add code to the OnInitDialog and OnOK functions to set and retrieve the date with the control's Value property.

12. Connect the dialog to the view.

a. Use ClassWizard to map the WM_LBUTTONDOWN message, and then edit the handler function as follows:

void ActiveXView::OnLButtonDown(UINT nFlags, CPoint point) { CActiveXDialog dlg; dlg.m_BackColor = RGB(255, 251, 240); // light yellow COleDateTime today = COleDateTime::GetCurrentTime(); dlg.m_varValue = COleDateTime(today.GetYear(), today.GetMonth(), today.GetDay(), 0, 0, 0); if (dlg.DoModal() == IDOK) { COleDateTime date(dlg.m_varValue); AfxMessageBox(date.Format("%B %d, %Y")); }}The code sets the background color to light yellow and the date to today's date, displays the modal dialog, and reports the date returned by the Calendar control. Then need to include the following in ActiveXView.cpp.#include ActiveXDialog.h13. Edit the virtual OnDraw function in the file ActiveXView.cpp.

a. To prompt the user to press the left mouse button, replace the code in the view class OnDraw function with this single line:

pDC->TextOut(0, 0, "Press the left mouse button here