You are on page 1of 128

REG.

NO:

NAME:

Ex.No. 1 Date:

KEYBOARD & MOUSE EVENTS

AIM: To write a Windows SDK program for performing keyboard and mouse events. PROCEDURE: STEP 1: Start the process. STEP 2: Open Microsoft Visual C++ by selecting Microsoft Visual C++ 6.0 from Visual Studio. STEP 3: Go to File->New and select the Projects tab in the New Dialog box. Select Win32 application from the list. STEP 4: Enter the Project name and select the desired location and click OK. STEP 5: Select A simple Win32 application in the next step and click Finish. To confirm, click OK.

STEP 6: Go to File->New and select the Files tab in the New dialog box. Select C++ Source file from the list. STEP 7: Enter the file name and click OK

REG.NO:

NAME:

STEP 8: Include the header file <windows.h> STEP 9: Declare structure variables for WNDCLASS, MSG and HWND. STEP 10: Declare the function WNDPROC. STEP 11: Assign WNDCLASS structure variable in WinMain. STEP 12: Register the WNDCLASS structure. STEP 13: Create window with the following arguments: name of the class, text that appear on the surface, the style of the window, the position, size, handle to the parent window, handle to the menu, application instance and pointer to the window creation data. STEP 14: Display the window. STEP 15: In window procedure using WM_LBUTTONDOWN, WM_CHAR, WM_RBUTTONDOWN, WM_KEYUP, WM_KEYDOWN perform mouse and keyboard operations. STEP 16: Build and Execute the application.

REG.NO:

NAME:

CODING: #include<windows.h> #include<stdio.h> #include<string.h> long _stdcall MyFunction(HWND,UINT,UINT,long); WNDCLASS obj; int flag;int x1,y1,x2,y2; int _stdcall WinMain(HINSTANCE a,HINSTANCE b,char *c,int d) { HWND hnd; MSG msg; obj.hInstance = a; obj.lpszClassName = "Myclass"; obj.lpfnWndProc = MyFunction; obj.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH); RegisterClass(&obj); hnd=CreateWindow("MyClass","Window Application for Keyboard Events",WS_OVERLAPPEDWINDOW,10,10,300,300,0,0,a,0); ShowWindow(hnd,1); UpdateWindow(hnd); while(GetMessage(&msg,0,0,0)) { TranslateMessage(&msg); DispatchMessage(&msg); } return msg.wParam; } long _stdcall MyFunction(HWND i,UINT j,UINT k,LPARAM l) { char left[]="You have Pressed Left Mouse Button"; char right[]="You have Pressed Right Mouse Button"; HDC dev; char str[100] =" "; switch(j) { case WM_CHAR: dev = GetDC(i); sprintf(str,"The Character is %c\n",(char)k); TextOut(dev,1,1,str,strlen(str)); ReleaseDC(i,dev); break; case WM_KEYDOWN: strcpy(str,"The Key is Down\n");

REG.NO:

NAME:

switch((char)k) { case VK_UP: strcat(str,"Up Arrow key pressed\n"); break; case VK_DOWN: strcat(str,"Down Arrow key Pressed\n"); break; case VK_LEFT: strcat(str,"Left Arrow key Pressed\n"); break; case VK_RIGHT: strcat(str,"Right Arrow key Pressed\n"); break; case VK_SHIFT: strcat(str,"Shift key Pressed\n"); break; case VK_HOME: strcat(str,"Home key Pressed\n"); break; case VK_END: strcat(str,"End key Pressed\n"); break; } strcat(str," "); dev = GetDC(i); TextOut(dev,1,1,str,strlen(str)); ReleaseDC(i,dev); break; case WM_LBUTTONDOWN: if(flag==0) { x1=LOWORD(l); y1=HIWORD(l); flag=1; } break; case WM_MOUSEMOVE: if(flag=1) { x2=LOWORD(l); y2=HIWORD(l); dev=GetDC(i); MoveToEx(dev,x1,y1,0); LineTo(dev,x2,y2);
4

REG.NO:

NAME:

ReleaseDC(i,dev); x1=x2; y1=y2; } break; case WM_LBUTTONUP: flag=0; break; case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(i,j,k,l); } return 0L; } OUTPUT:

RESULT: Thus the above program has been executed successfully and output is verified.

REG.NO:

NAME:

Ex.No. 2 Date:

DIALOG BASED APPLICATION

AIM: To write a Visual C++ program for Dialog Based Application. PROCEDURE: STEP 1: Start VC++->File->New. Then select win32 Application in the Appwizard and give the project name as dial2 ->click OK->then Finish.

STEP 2: Click Insert->Resource from the menu and then select the Dialog option and then click New.

REG.NO:

NAME:

STEP 3: Design the dialog window using the controls in the tool bar.

STEP 4: Change the ID for controls. Control Type Edit Control List Box Button (ADD) Button (EXIT) ID ID_EB1 IDC_LIST1 IDOK IDCANCEL

STEP 5: Select the Insert->Resource from the menu and then select the option Menu from it. The menu contains one main menu and one pop menu named (Load and EditBox).

(If the EDITBOX options is clicked dialog box containing the controls will be displayed. If the EXIT option is select from the DialogBox the output window will be closed.)

REG.NO:

NAME:

STEP 6: Close the dialog window and save by giving a name to be Script. This will be stored with .rc extension, include this file and resource header file (resource.h) to the project by clicking Project- >Add to Project->Files. Now select the .rc and resource.h files in the project and click ok.

STEP 7: Click file -> New and then select the option C++ source file and give the name to the file as Control.Cpp. Enter the code in Control.Cpp. STEP 8: Type the following code in the Control.cpp file and build the application. //Control.cpp: #include<windows.h> #include<stdio.h> #include"resource.h" long _stdcall MyFunction(HWND,UINT,UINT,long); BOOL CALLBACK MyDialogFunction(HWND,UINT,WPARAM,LPARAM); WNDCLASS obj; HINSTANCE hInst; int _stdcall WinMain(HINSTANCE a,HINSTANCE b,char *c,int d) { HWND hnd; MSG str; obj.hInstance=a; obj.lpszClassName ="Myclass"; obj.lpfnWndProc =MyFunction; obj.lpszMenuName=MAKEINTRESOURCE(IDR_MENU1); obj.hbrBackground=(HBRUSH)GetStockObject(WHITE_BRUSH); 8

REG.NO:

NAME: RegisterClass(&obj); hnd=CreateWindow("Myclass","Edit Box Demo",WS_OVERLAPPEDWINDOW,10,10,450,300,0,0,a,0); hInst=a; ShowWindow(hnd,1); while(GetMessage(&str,0,0,0)) { DispatchMessage(&str); } return 0;

} long _stdcall MyFunction(HWND i,UINT j,WPARAM k,long l) { switch(j) { case WM_COMMAND: switch(LOWORD(k)) { case ID_LOAD_EDITBOX: DialogBox(hInst,MAKEINTRESOURCE(IDD_DIALOG1),i, (DLGPROC)MyDialogFunction); break; } break; case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(i,j,k,l); } return 0L;} BOOL CALLBACK MyDialogFunction(HWND w,UINT x,WPARAM y,LPARAM z) { char str[70]; switch(x) { case WM_COMMAND: switch(LOWORD(y)) { case IDCANCEL: EndDialog(w,0); return 1; case IDOK: GetDlgItemText(w,ID_EB1,str,70); SendDlgItemMessage(w,IDC_LIST1,LB_ADDSTRING,0, (LPARAM)str); MessageBox(w,str,"Item Selection",MB_OK); return 1; } break; 9

REG.NO: } return 0; } OUTPUT:

NAME:

10

REG.NO:

NAME:

RESULT: Thus the above program has been executed successfully and output is verified.

11

REG.NO:

NAME:

Ex.No. 3(a) Date: AIM:

CREATING SDI APPLICATION

To write a Visual C++ a program to create SDI Applications. PROCEDURE: STEP 1: Start VC++->File->New. Then select MFCApplicationWizard(.exe),and give project name as sdi. Then click OK button.

STEP 2: Select the option Single Document and then click finish button.

12

REG.NO:

NAME:

STEP 3: Press Ctrl+W to open Class Wizard->Message Maps.Choose the class name CSdiView and add a function to the message WM_CHAR.

STEP 4: Build and Execute the application. //sdiDoc.h class CSdiDoc : public CDocument { Protected: .. // Attributes public: CString text; // Operations //sdiDoc.cpp // CSdiDoc construction/destruction CSdiDoc::CSdiDoc() { // TODO: add one-time construction code here text=""; } // sdiView.cpp #include "StdAfx.h" #include "sdi.h" #include "sdiDoc.h"
13

REG.NO:

NAME:

#include "sdiView.h" #ifdef _DEBUG // CSdiView drawing void CSdiView::OnDraw(CDC* pDC) { CSdiDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); pDC->TextOut(50,50,pDoc->text); // TODO: add draw code for native data here } // CSdiView message handlers void CSdiView::OnChar(UINT nChar, UINT nRepCnt, UINT nFlags) { // TODO: Add your message handler code here and/or call default CSdiDoc* pDoc=GetDocument(); ASSERT_VALID(pDoc); pDoc->text+=nChar; CView::OnChar(nChar, nRepCnt, nFlags); } OUTPUT:

RESULT: Thus the above program has been executed successfully and output is verified.

14

REG.NO:

NAME:

Ex.No. 3(b) Date: AIM: To write a Visual C++ program to creating the MDI applications. PROCEDURE: STEP 1: Start VC++ program. Select File-> New -> MFC AppWizard(exe). Give the project name as MDIDemo. Then select the Multiple Document Interface option. CREATING MDI APPLICATION

15

REG.NO:

NAME:

STEP2: Click Next button step 2 to 5. for the step6 select the base class as CEditView. And click the finish button.

STEP 3: Now open the file MDIDemo.cpp and add the message in OpenDocumentFile for the class CMDIDemoApp.

Then write the following code in the MDIDemo.cpp in OpenDocumentFile Message Handler // CMDIDemoApp message handlers CDocument* CMDIDemoApp::OpenDocumentFile(LPCTSTR lpszFileName) { // TODO: Add your specialized code here and/or call the base class TRACE("the application is in open document file"); return CWinApp::OpenDocumentFile(lpszFileName); }

16

REG.NO:

NAME:

Using the above code, we can keep track of the Instance at which the application is opening document File. This happens on executing the program and when we Click on theopen menu item from the file on the menubar STEP 4: Then open MDIDemoView.cpp file and edit the OnDraw() function and write the following code void CMDIDemoView::OnDraw(CDC* pDC) { CMDIDemoDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); // TODO: add draw code for native data here CString msg="this is"; msg+=pDoc->GetTitle(); pDC->TextOut(10,10,msg); } STEP 5: Next we will open the ChildFrm.cpp file. Now for invoke the class wizard for adding the message handler for the class CChildFrame. The message ActiveFrame will be added. And Edit the following code.

void CChildFrame::ActivateFrame(int nCmdShow) { // TODO: Add your specialized code here and/or call the base class TRACE("entering in the child window "); CMDIChildWnd::ActivateFrame(nCmdShow); } STEP 6: Then Add the another message DestroyWindow for the class CChildFrame. And edit the following code in ChildFrm.cpp file

17

REG.NO:

NAME:

BOOL CChildFrame::DestroyWindow() { // TODO: Add your specialized code here and/or call the base class TRACE("Destroying the child frame"\n"); return CMDIChildWnd::DestroyWindow(); } STEP 7: Build and Execute the application . OUTPUT:

RESULT: Thus the above program has been executed successfully and output is verified.
18

REG.NO:

NAME:

Ex.No:4 Date : AIM:

DOCUMENT-VIEW ARCHITECTURE

To write a Visual C++ program for creating a Document View Architecture. PROCEDURE: STEP 1: Start VC++ Click on File New. Then select MFC Application(exe). Then in the Edit window of Project name give the name as DVDemo. Click OK. STEP 2: Select Single Document Interface option. STEP 3: Click Next button for the steps 2 to 5 by accepting the default values. STEP 4: Now choose the base class as CFormView instead of CView. Click Finish.

STEP 5: In the Dialog resource we will get IDD_DVDEMO_FORM.Just click on it and modify it as follows.

19

REG.NO:

NAME:

Ensure that the property of this form is style=child, Border=None and Visible=Unchecked. Control EditBox Button ID IDC_EDIT1 IDC_BUTTON1 Additional properties Visible and TAbStop is checked. Caption = Send. Visible and Tab Stop is checked

STEP6: Invoke class wizard and click on the Add variable. Click on the IDC_EDIT1 and add the variable m_str of the type CString. Then click on the message maps to add the message for the IDC_BUTTON1 Ensure that the class name is CDVDemoView . Add the message BN_CLICKED which in turn yield the member function Onsend(). STEP 7: (i)Click on the Class view. Right click on CDVDemoView and choose Add member function and add the user defined function DataFromDoc of private access mode. .

STEP 8: Now open DVDemoView.cpp file and call the function DataFromDoc in the function OnInitialUpdate function. void CDVDemoView::OnInitialUpdate() { DataFromDoc();// Transferring data from document to view } STEP 9: Click on the File View and then click File->New from the menu bar to add new .cpp and .h files. Create empty MyMessage.h and MyMessage.cpp files. The MyMessage.h and MyMessage.cpp files are added in this project for building them together with the rest of the application framework. These files can be written as follows:

20

REG.NO:

NAME:

MyMessage.h #ifndef _INSIDE_VISUAL_CPP_MYMESSAGE #define _INSIDE_VISUAL_CPP_MYMESSAGE class CMyMessage:public CObject { DECLARE_DYNAMIC(CMyMessage) public: CString m_MyMessage; CMyMessage() { m_MyMessage=_T(" "); } CMyMessage(const char* szInput):m_MyMessage(szInput) { m_MyMessage=_T(" "); } CMyMessage(const CMyMessage&Msg_Obj):m_MyMessage(Msg_Obj.m_MyMessage) { m_MyMessage=Msg_Obj.m_MyMessage; } const CMyMessage& operator=(const CMyMessage& Msg_Obj) { m_MyMessage=Msg_Obj.m_MyMessage; return *this; } BOOL operator==(const CMyMessage& Msg_Obj)const { if((m_MyMessage == Msg_Obj.m_MyMessage)) { return TRUE; } else { return FALSE; } } BOOL operator!=(const CMyMessage& Msg_Obj)const { return!(*this == Msg_Obj); } #ifdef _DEBUG void Dump(CDumpContext& dc)const; #endif }; #endif
21

REG.NO:

NAME:

MyMessage.cpp #include"stdafx.h" #include"MyMessage.h" IMPLEMENT_DYNAMIC(CMyMessage,CObject) #ifdef _DEBUG void CMyMessage::Dump(CDumpContext& dc)const { CObject::Dump(dc); dc<<"m_str="<<m_MyMessage<<"\n"; } #endif STEP10: Then open DVDemoDoc.h and add the data member for the class // Implementation public: CMyMessage m_MyMessage; Or Click on the Class view. Right click on CDVDemoDoc and choose Add member varaiable of Type CMyMesssage and variable name as m_MyMessage in public access mode(automatically the above line will be added). Here CMyMessage is a constructor which gets constructed when the document object gets constructed.

STEP 11: Go to File View and open the DVDemoView.cpp file and make following changes

22

REG.NO:

NAME:

void CDVDemoView::Onsend() { // TODO: Add your control notification handler code here CDVDemoDoc* pDoc=GetDocument(); UpdateData(TRUE); pDoc->m_MyMessage.m_MyMessage=m_str; } void CDVDemoView::DataFromDoc() { CDVDemoDoc* pDoc = GetDocument(); m_str=pDoc->m_MyMessage.m_MyMessage; UpdateData(FALSE); }

STEP12: Now edit the DVDemoDoc.cpp file as follows: // CDVDemoDoc construction/destruction CDVDemoDoc::CDVDemoDoc():m_MyMessage("Default Message") { TRACE("Document object constructed"); } TRACE macro is similar to the printf statement in C language. It is active when debug mode is active. So. What ever we write in TRACE statement can be seen in the debug window during debugging mode. Then dump function is called to dump the document on exiting. Hence modify the destructor and dump function as followsCDVDemoDoc::~CDVDemoDoc() { #ifdef _DEBUG Dump(afxDump); #endif }
23

REG.NO:

NAME:

void CDVDemoDoc::Dump(CDumpContext& dc) const { CDocument::Dump(dc); dc<<"\n"<<m_MyMessage<<"\n"; } #endif //_DEBUG

STEP13: Build the program and then start in debugging mode while executing. Following form window will appear just type some message in the edit box and then press Send button.

Now just click x and close the form window. Then see the Debug window which displays the output:

24

REG.NO:

NAME:

OUTPUT:

RESULT: Thus the document view architecture program has been build and executed successfully.

25

REG.NO:

NAME:

Ex.No:5 Date: AIM:

CALCULATOR USING DYNAMIC CONTROLS

To write a calculator program for dialog based application using Visual C++. PROCEDURE: STEP 1: Start VC++ -> File -> New -> MFC AppWizard(exe).Give the project name as calculator. Select the option Dialog Based. Click Next button and finish for getting the skeleton code.

STEP 2: The default dialog box will be obtained. Just delete the OK and Cancel buttons. Delete TODO: static box. Design the dialog box as follows:

26

REG.NO:

NAME:

The controls that are placed on the dialog box are summarized as follows: Name of Control Static Text Static Text Static Text Edit Box Edit Box Edit Box Button Button Button Button Button Button Button Button Object ID IDC_STATIC IDC_STATIC IDC_STATIC IDC_EDIT1 IDC_EDIT2 IDC_EDIT3 IDC_ADD IDC_SUB IDC_MUL IDC_DIV IDC_SQR IDC_CE IDC_MR IDC_CM Properties Caption=NUMBER 1 Caption=NUMBER 2 Caption=RESULT

Caption=+ Caption=- Caption=* Caption=/ Caption=x^2 Caption=CE Caption=MEMORY FOR RESULT Caption=CLEAR MEMORY

STEP 3: Invoke the Class Wizard. Add the member variables for three edit boxes as follows: MEMBER VARIABLE IDC_EDIT1 IDC_EDIT2 IDC_EDIT3 NAME m_val1 m_val2 m_ans TYPE Float Float CString

Then go to the Class View of the workspace. Right click on the class CCalculatorDlg and add the member variable as follows:

27

REG.NO:

NAME:

STEP 4: These variables can be initialized in the OnInitDialog function BOOL CCalculatorDlg::OnInitDialog() { // TODO: Add extra initialization here m_val1=0; m_val2=0; temp=0; return TRUE; // return TRUE unless you set the focus to a control } STEP 5: Now for the CCalculatorDlg class add the message BN_CLICKED for all the buttons that are placed on the dialog box.

We will get the default message handler functions for which the code can be written as follows: //calculatorDlg.cpp: void CCalculatorDlg::Onadd() { // TODO: Add your control notification handler code here UpdateData(TRUE); temp=m_val1+m_val2; m_ans.Format("%.2f",temp); UpdateData(FALSE);
28

REG.NO:

NAME:

} void CCalculatorDlg::Onsub() { // TODO: Add your control notification handler code here UpdateData(TRUE); temp=m_val1-m_val2; m_ans.Format("%.2f",temp); UpdateData(FALSE); } void CCalculatorDlg::Onmul() { // TODO: Add your control notification handler code here UpdateData(TRUE); temp=m_val1*m_val2; m_ans.Format("%.2f",temp); UpdateData(FALSE); } void CCalculatorDlg::Ondiv() { // TODO: Add your control notification handler code here UpdateData(TRUE); if(m_val2==0) { MessageBox("Divide By Zero!!!","ERROR"); return; } else { temp=m_val1/m_val2; m_ans.Format("%.2f",temp); UpdateData(FALSE); }} void CCalculatorDlg::Onsqr() {// TODO: Add your control notification handler code here UpdateData(TRUE); temp=m_val1*m_val1; m_ans.Format("%.2f",temp); UpdateData(FALSE); } void CCalculatorDlg::Ononce() { // TODO: Add your control notification handler code here m_val1=0; m_val2=0; UpdateData(FALSE); }
29

REG.NO:

NAME:

void CCalculatorDlg::Onmem() { // TODO: Add your control notification handler code here m_val1=temp; UpdateData(FALSE); } void CCalculatorDlg::Onclr() { // TODO: Add your control notification handler code here m_val1=0; m_val2=0; temp=0; m_ans.Format("%.2f",temp); UpdateData(FALSE); } STEP 6: Build the application and following output can be obtained. OUTPUT:

RESULT: Thus the above program has been executed successfully and output is verified. Ex.No:6

COURSE REGISTRATION USING DYNAMIC CONTROLS


30

REG.NO:

NAME:

Date:

AIM: To write a visual C++ program for Course Registration using Dynamic controls. PROCEDURE: STEP 1:Start VC++.Click New on the menu bar and select the MFC Application(exe).Give the project name as course.Select the Dialog Based radio button.Click button and finally click the finish button to get the skeleton code.

STEP 2:Select the Dialog Based radio button.Click Next button and finally click the finish button.

STEP 3:Place the controls in the dialog box.

STEP 4:Set the combo box items for course by clicking the Data tab.
31

REG.NO:

NAME:

STEP 5:Set the member variables m_list for the List Box control of the type CListBox.Also add the variable name m_name for the Edit Box of Students Name which is of the type CString.

STEP 6:Then for the Add button add the message handler function using BN_CLICKED message.Also add the message WM_CTLCOLOR.

//courseDlg.cpp:
32

REG.NO:

NAME:

CCourseDlg::CCourseDlg(CWnd* pParent /*=NULL*/) : CDialog(CCourseDlg::IDD, pParent) { //{{AFX_DATA_INIT(CCourseDlg) m_name = _T(""); //}}AFX_DATA_INIT // Note that LoadIcon does not require a subsequent DestroyIcon in Win32 m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); } void CCourseDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CCourseDlg) DDX_Control(pDX, IDC_LIST2, m_list); DDX_Text(pDX, IDC_EDIT1, m_name); //}}AFX_DATA_MAP } void CCourseDlg::Onadd() { // TODO: Add your control notification handler code here CString str; UpdateData(); str=m_name; UpdateData(FALSE); m_list.AddString(str); } HBRUSH CCourseDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor) { HBRUSH hbr = CDialog::OnCtlColor(pDC, pWnd, nCtlColor); HBRUSH m_greenBrush=CDialog::OnCtlColor(pDC,pWnd,nCtlColor); HBRUSH m_redBrush=CDialog::OnCtlColor(pDC,pWnd,nCtlColor); if(nCtlColor==CTLCOLOR_EDIT) { pDC->SetBkColor(RGB(150,120,0)); return m_greenBrush; //TODO:Return a different brush if the default is not desired } if(nCtlColor==CTLCOLOR_DLG) { pDC->SetBkColor(RGB(255,0,0)); return m_redBrush; } return hbr; } STEP 7:Build and Execute the Application. OUTPUT:
33

REG.NO:

NAME:

RESULT: Thus the above program has been executed successfully and output is verified

34

REG.NO:

NAME:

Ex.No:7 Date: AIM:

WINDOWS COMMON CONTROL

To create various windows common control using MFC AppWizard. PROCEDURE: LIST CONTROL STEP 1: Start Visual C++.Select the MFC AppWizard(exe) from New. Select the Dialog Based Application. STEP 2: The default dialog box will appear on the screen.Then click on the list control and drag it on the dialog box.Then set the ID for the list control.Then click the styles tab and set the view as Report. STEP 3: Invoke the class wizard and add the member variable as m_name which is of the type CListCtrl and then add the function for the message handler LVN_INSERTITEM for the List Control. STEP 4:Add the following code on the OnInitDialog() method. BOOL CListcontrolDlg::OnInitDialog() { // TODO: Add extra initialization here LVCOLUMN c1; c1.mask=LVCF_FMT|LVCF_TEXT|LVCF_WIDTH; c1.fmt=LVCFMT_LEFT; c1.cx=120; c1.pszText="Name"; m_name.InsertColumn(0,&c1); c1.mask=LVCF_FMT|LVCF_TEXT|LVCF_WIDTH; c1.fmt=LVCFMT_LEFT; c1.cx=75; c1.pszText="Pin"; m_name.InsertColumn(1,&c1); c1.mask=LVCF_FMT|LVCF_TEXT|LVCF_WIDTH; c1.fmt=LVCFMT_LEFT; c1.cx=80; c1.pszText="City"; m_name.InsertColumn(2,&c1); c1.mask=LVCF_FMT|LVCF_TEXT|LVCF_WIDTH; c1.fmt=LVCFMT_LEFT;
35

REG.NO:

NAME:

c1.cx=75; c1.pszText="Contact"; m_name.InsertColumn(3,&c1); LVITEM i1; int n; i1.mask=LVIF_TEXT; i1.iItem=0; i1.iSubItem=0; i1.pszText="Anu"; n=m_name.InsertItem(&i1); m_name.SetItemText(n,1,"5433"); m_name.SetItemText(n,2,"Cbe"); m_name.SetItemText(n,3,"9888778893"); i1.mask=LVIF_TEXT; i1.iItem=1; i1.iSubItem=0; i1.pszText="Ammu"; n=m_name.InsertItem(&i1); m_name.SetItemText(n,1,"9876"); m_name.SetItemText(n,2,"Erode"); m_name.SetItemText(n,3,"9099867763"); i1.mask=LVIF_TEXT; i1.iItem=2; i1.iSubItem=0; i1.pszText="Praneet"; n=m_name.InsertItem(&i1); m_name.SetItemText(n,1,"0093"); m_name.SetItemText(n,2,"Salem"); m_name.SetItemText(n,3,"9006546883"); i1.mask=LVIF_TEXT; i1.iItem=3; i1.iSubItem=0; i1.pszText="Raja"; n=m_name.InsertItem(&i1); m_name.SetItemText(n,1,"5223"); m_name.SetItemText(n,2,"Chennai"); m_name.SetItemText(n,3,"8088776883"); return TRUE; // return TRUE unless you set the focus to a control } STEP 6: Build the program and you will get the following output.

OUTPUT:
36

REG.NO:

NAME:

SPIN CONTROL STEP 1: Start Visual C++.Select the MFC AppWizard(exe) from New. Select the Dialog Based Application. STEP 2: The default dialog box will appear on the screen.Then select the spin control and place it on the dailog box.Then palce the deit box control on the dialog box

STEP 3: Click on the Style tab for the Spin button and make the settings as follows.Dont forget to check buddy and set buddy integer options. STEP 4: Using Class Wizard the variables can be set for Edit Box and Spin Button as follows:

ID

TYPE

MEMBER VARIABLE

37

REG.NO:
IDC_EDIT1 IDC_SPIN1 Int CSpinButtonCtrl

NAME:
m_val m_sval

STEP 5: Click on the Message Maps to set the Message handler functions.Double click on the messages WM_INITDIALOG and WM_SCROLL to add the member variable. CSpinDlg::CSpinDlg(CWnd* pParent /*=NULL*/) : CDialog(CSpinDlg::IDD, pParent) { //{{AFX_DATA_INIT(CSpinDlg) m_val = 0; //}}AFX_DATA_INIT } BOOL CSpinDlg::OnInitDialog() { // TODO: Add extra initialization here CSpinButtonCtrl* ptr=(CSpinButtonCtrl*)GetDlgItem(IDC_SPIN1); ptr->SetRange(0,100); return TRUE; // return TRUE unless you set the focus to a control } void CSpinDlg::OnVScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar) { // TODO: Add your message handler code here and/or call default if(nSBCode==SB_ENDSCROLL) { return; } if(pScrollBar->GetDlgCtrlID()==IDC_SPIN1) { CString val; val.Format("%d",nPos); ((CSpinButtonCtrl*)pScrollBar)->GetBuddy()->SetWindowText(val); } CDialog::OnVScroll(nSBCode, nPos, pScrollBar); } STEP 6: Build the application and get the following ouput.

OUTPUT:
38

REG.NO:

NAME:

PROGRESS BAR STEP 1: Start Visual C++.Select the MFC AppWizard(exe) from New. Select the Dialog Based Application. STEP 2: Using the GetPos method the value indicated by the Progress Bar can be obtained.Then displaying this value using the static text control. BOOL CProgressbarDlg::OnInitDialog() { // TODO: Add extra initialization here CProgressCtrl *prog=new CProgressCtrl; Prog- >Create(WS_CHILD|WS_VISIBLE,CRect(10,10,300,30),this,0X16); prog->SetRange(1,100); prog->SetPos(35); int cpos=prog->GetPos(); CString str; str.Format("%d",cpos); SetDlgItemText(IDC_STATIC,str); return TRUE; // return TRUE unless you set the focus to a control } STEP 3: Build and execute it to get the following output.

OUTPUT:
39

REG.NO:

NAME:

SLIDER CONTROL STEP 1: Start Visual C++.Select the MFC AppWizard(exe) from New. Select the Dialog Based Application. STEP 2:After placing the spider control on the dialog box,just set the desired properties of the spider control.Then place one static text control.

STEP 3:Set the member variable for the slider control as m_sval which is of the control type.Hence its data type is CSliderCtrl. ID IDC_SLIDER1 VARIABLE NAME m_sval VARIABLE TYPE CSliderCtrl

STEP 4:Set the message handlers click on the message WM_HSCROLL and then add the function.
40

REG.NO:

NAME:

BOOL CSliderctrlDlg::OnInitDialog() { CDialog::OnInitDialog(); // Add "About..." menu item to system menu. // IDM_ABOUTBOX must be in the system command range. ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX); ASSERT(IDM_ABOUTBOX < 0xF000); CMenu* pSysMenu = GetSystemMenu(FALSE); if (pSysMenu != NULL) { CString strAboutMenu; strAboutMenu.LoadString(IDS_ABOUTBOX); if (!strAboutMenu.IsEmpty()) { pSysMenu->AppendMenu(MF_SEPARATOR); pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu); } } // Set the icon for this dialog. The framework does this automatically // when the application's main window is not a dialog SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon // TODO: Add extra initialization here CSliderCtrl* slider=(CSliderCtrl*)GetDlgItem(IDC_SLIDER1); slider->SetRange(1,10); slider->SetTicFreq(1); return TRUE; // return TRUE unless you set the focus to a control } void CSliderctrlDlg::OnHScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar) { // TODO: Add your message handler code here and/or call default CString str; int i=m_sval.GetPos(); str.Format("%d",i); SetDlgItemText(IDC_STATIC,str); CDialog::OnHScroll(nSBCode, nPos, pScrollBar); } STEP 5: Execute the above program to get the following output. OUTPUT:
41

REG.NO:

NAME:

TREE CONTROL STEP 1: Start Visual C++.Select the MFC AppWizard(exe) from New. Select the Dialog Based Application. STEP 2: Drag and place the Tree control on the tool bar. STEP 3: Create this control using following code on the OnInitDialog() function. BOOL CTreeDlg::OnInitDialog() { CDialog::OnInitDialog(); CTreeCtrl *tree; tree=new CTreeCtrl; // TODO: Add extra initialization here Tree>Create(WS_CHILD|WS_VISIBLE|WS_BORDER|WS_TABSTOP| TVS_HASLINES|TVS_HASBUTTONS,CRect(10,10,250,300),this,0X1221); HTREEITEM item,fruit,color,shape,taste; item=tree->InsertItem("Item"); fruit=tree->InsertItem("Fruit",item); color=tree->InsertItem("Color",item); shape=tree->InsertItem("Shape",item); taste=tree->InsertItem("Apple",fruit); tree->InsertItem("Mango",fruit); tree->InsertItem("Banana",fruit); tree->InsertItem("Red",color); tree->InsertItem("Green",color); tree->InsertItem("Blue",color); tree->InsertItem("Rectangle",shape);
42

REG.NO:

NAME:

tree->InsertItem("Circle",shape); tree->InsertItem("Square",shape); return TRUE; // return TRUE unless you set the focus to a control } STEP 4: Build and Execute the application and get the following output. OUTPUT:

RESULT: Thus the various windows common controls created using MFC AppWizard. Ex.No:8

RICH EDIT BOX CONTROL

43

REG.NO:

NAME:

Date: AIM: To create a Rich Edit Box Control for various format of text using MFCAppWizard(exe). PROCEDURE: STEP 1: Start VC++ application. Select File-> New->MFCAppWizard(exe).Give project name as richeditdemo. Then select Single Document and deselect Printing and Print Preview option.

The skeleton code gets generated. STEP 2: Click on Resource tab and in that select->Menu folder.The default ID_IDR_MAINFRAME appears in that add Menu and Menu-Item Menu Edit Data Transaction Data Transaction Text Format Text Format Text Format Text Format Text Format Text Format Text Format Alignment Alignment Alignment Caption Erase &All Read Data From Document\tF4 &Save Data in Document\tF5 Bold Italics Strike Through Underline Subscript Superscript Normal Left Align Right Align Cente Align menu is

Command-ID ID_EDIT_ERASE ID_DATATRANSACTION_READDATA ID_DATATRANSACTION_SAVEDATA ID_TEXTFORMAT_BOLD ID_TEXTFORMAT_ITALICS ID_TEXTFORMAT_ STRIKETHROUGH ID_TEXTFORMAT_UNDERLINE ID_TEXTFORMAT_ SUBSCRIPT ID_TEXTFORMAT_ SUPERSCRIPT ID_TEXTFORMAT_NORMAL ID_ALIGNMENT_LEFTALIGN ID_ALIGNMENT_RIGHTALIGN ID_ALIGNMENT_CENTERALIGN
44

REG.NO:

NAME:

STEP 3: Set the Keyword Accelerators by opening the IDR_MAINFRAME accelerator table

Accelerator ID
ID_DATATRANSACTION_READDATA ID_DATATRANSACTION_SAVEDATA

Key
VK_F4 VK_F5

Ctrl, Alt and Shift modifiers are unchecked. STEP 4: Invoke the Class Wizard to set the COMMAND and messages for ID_EDIT_ERASEALL. STEP 5: Open the file richeditdemoDoc.h to add the variable as public: CString m_str; STEP 6: Open the richeditdemoDoc.cpp file and edit the OnNewDocument(), OnEditEraseall() function as follow BOOL CRicheditdemoDoc::OnNewDocument()
45

UPDATE_COMMAND_UI

REG.NO:

NAME:

{ // TODO: add reinitialization code here // (SDI documents will reuse this document) m_str="New Document File"; return TRUE; } void CRicheditdemoDoc::OnEditEraseall() { // TODO: Add your command handler code here m_str.Empty(); } void CRicheditdemoDoc::OnUpdateEditEraseall(CCmdUI* pCmdUI) { // TODO: Add your command update UI handler code here pCmdUI->Enable(!m_str.IsEmpty()); } STEP 7: Open the richeditdemoView.h to add the variable as
public: CRichEditCtrl m_richbox;

STEP 8: Invoke the Class Wizard to map the message WM_CREATE and WM_SIZE message for the class CricheditdemoView void CRicheditdemoView::OnSize(UINT nType, int cx, int cy) { CRect m_rect; CView::OnSize(nType, cx, cy); // TODO: Add your message handler code here GetClientRect(m_rect); m_richbox.SetWindowPos(&wndTop,0,0,m_rect.right-m_rect.left, m_rect.bottom-m_rect.top,SWP_SHOWWINDOW); } int CRicheditdemoView::OnCreate(LPCREATESTRUCT lpCreateStruct) { CRect m_rect(0,0,0,0); if (CView::OnCreate(lpCreateStruct) == -1) return -1; // TODO: Add your specialized creation code here m_richbox.Create(ES_AUTOVSCROLL|ES_MULTILINE|ES_WANTRETURN| WS_CHILD|WS_VISIBLE|WS_VSCROLL,m_rect,this,1); return 0; } STEP 9: Invoke the class wizard add the COMMAND message for each of the menu item for the class CricheditdemoView.
46

REG.NO:

NAME:

Command_ID
ID_DATATRANSACTION_READ DATA ID_DATATRANSACTION_SAVE DATA ID_TEXTFORMAT_BOLD ID_TEXTFORMAT_ITALICS ID_TEXTFORMAT_ STRIKETHROUGH ID_TEXTFORMAT_UNDERLINE ID_TEXTFORMAT_ SUBSCRIPT ID_TEXTFORMAT_ SUPERSCRIPT ID_TEXTFORMAT_NORMAL ID_ALIGNMENT_LEFTALIGN ID_ALIGNMENT_RIGHTALIGN ID_ALIGNMENT_CENTERALIGN

Message
COMMAND COMMAND COMMAND COMMAND COMMAND COMMAND COMMAND COMMAND COMMAND COMMAND COMMAND COMMAND

Message Handler
OnDatatransactionReaddatafrom document OnDatatransactionSavedataindoc ument OnTextformatBold OnTextformatItalics OnTextformatStrikethroug OnTextformatUnderline OnTextformatSubscript OnTextformatSuperscript OnTextformatNormal OnAlignmentLeftalign OnAlignmentRightalign OnAlignmentCenteralign

void CRicheditdemoView::OnDatatransactionReaddatafromdocument() { // TODO: Add your command handler code here CRicheditdemoDoc *pDoc=GetDocument(); m_richbox.SetWindowText(pDoc->m_str); m_richbox.SetModify(FALSE); } void CRicheditdemoView::OnDatatransactionSavedataindocument() { // TODO: Add your command handler code here CRicheditdemoDoc *pDoc=GetDocument(); m_richbox.GetWindowText(pDoc->m_str); m_richbox.SetModify(FALSE); } void CRicheditdemoView::OnUpdateDatatransactionSavedataindocument(CCmdUI* pCmdUI) { // TODO: Add your command update UI handler code here pCmdUI->Enable(m_richbox.GetModify()); } void CRicheditdemoView::OnTextformatBold() { // TODO: Add your command handler code here
47

REG.NO:

NAME:

CHARFORMAT fm; m_richbox.GetSelectionCharFormat(fm); fm.cbSize=sizeof(CHARFORMAT); fm.dwMask=CFM_BOLD; fm.dwEffects^=CFE_BOLD; m_richbox.SetSelectionCharFormat(fm); m_richbox.SetFocus(); } void CRicheditdemoView::OnTextformatItalics() { // TODO: Add your command handler code here CHARFORMAT fm; m_richbox.GetSelectionCharFormat(fm); fm.cbSize=sizeof(CHARFORMAT); fm.dwMask=CFM_ITALIC; fm.dwEffects^=CFE_ITALIC; m_richbox.SetSelectionCharFormat(fm); m_richbox.SetFocus(); } void CRicheditdemoView::OnTextformatStrikethrough() { // TODO: Add your command handler code here CHARFORMAT fm; m_richbox.GetSelectionCharFormat(fm); fm.cbSize=sizeof(CHARFORMAT); fm.dwMask=CFM_STRIKEOUT; fm.dwEffects^=CFE_STRIKEOUT; m_richbox.SetSelectionCharFormat(fm); m_richbox.SetFocus(); } void CRicheditdemoView::OnTextformatUnderline() { // TODO: Add your command handler code here CHARFORMAT fm; m_richbox.GetSelectionCharFormat(fm); fm.cbSize=sizeof(CHARFORMAT); fm.dwMask=CFM_UNDERLINE; fm.dwEffects^=CFE_UNDERLINE; m_richbox.SetSelectionCharFormat(fm); m_richbox.SetFocus(); } void CRicheditdemoView::OnTextformatSuperscript() { // TODO: Add your command handler code here CHARFORMAT fm; m_richbox.GetSelectionCharFormat(fm); fm.yHeight=200; fm.yOffset=55;
48

REG.NO:

NAME:

m_richbox.SetSelectionCharFormat(fm); } void CRicheditdemoView::OnTextformatSubscript() { // TODO: Add your command handler code here CHARFORMAT fm; m_richbox.GetSelectionCharFormat(fm); fm.yHeight=150; fm.yOffset=-50; m_richbox.SetSelectionCharFormat(fm); } void CRicheditdemoView::OnTextformatNormal() { // TODO: Add your command handler code here CHARFORMAT fm; m_richbox.GetSelectionCharFormat(fm); fm.yOffset=0; fm.yHeight=300; m_richbox.SetSelectionCharFormat(fm); } void CRicheditdemoView::OnAlignmentCenteralign() { // TODO: Add your command handler code here PARAFORMAT pfm; pfm.cbSize=sizeof(PARAFORMAT); pfm.dwMask=PFM_ALIGNMENT; pfm.wAlignment=PFA_CENTER; m_richbox.SetParaFormat(pfm); m_richbox.SetFocus(); } void CRicheditdemoView::OnAlignmentLeftalign() { // TODO: Add your command handler code here PARAFORMAT pfm; pfm.cbSize=sizeof(PARAFORMAT); pfm.dwMask=PFM_ALIGNMENT; pfm.wAlignment=PFA_LEFT; m_richbox.SetParaFormat(pfm); m_richbox.SetFocus(); } void CRicheditdemoView::OnAlignmentRightalign() { // TODO: Add your command handler code here PARAFORMAT pfm; pfm.cbSize=sizeof(PARAFORMAT); pfm.dwMask=PFM_ALIGNMENT; pfm.wAlignment=PFA_RIGHT;
49

REG.NO:

NAME:

m_richbox.SetParaFormat(pfm); m_richbox.SetFocus(); } STEP 10: Build the application, type some text in client area and format the text using Menu items. OUTPUT:

RESULT: Thus the text had been formatted with various styles of the menu item using rich edit control.

Ex.No:9

50

REG.NO:

NAME:

Date:

STATUS BAR

AIM:
To write a VC++ program to display the sensitive help for tool buttons or menu bar items.

PROCEDURE: STEP 1: Start VC++ application. Select File-> New-> MFC AppWizard(exe). Give the project name as StatusBarDemo. Then select the single document interface option. STEP 2: Click on the ResourceView tab and just right click on the root StatusBarDemo resources. Click on the Resource Symbols, click New and add ID_MYSTATUSBAR, accept the default value. This is the ID for our status bar. STEP 3: Then get the class wizard and add the messages as follows Object ID Message Function ID_VIEW_STATUS_BAR COMMAND OnViewStatusBar ID_VIEW_STATUS_BAR UPDATE_COMMAND_UI OnUpdateViewStatusBar Then Edit the code for this message handlers in the MainFrm.cpp file as//CMainFrame message handlers void CMainFrame::OnViewStatusBar() { //TODO: Add your command handler code here m_WndStatusBar.ShowWindow((m_wndStatusBar.GetBarStyle()&WS_VISIBL==0); RecalcLayout(); } void CMainFrame::onUpdateViewStatusBar(CCmdUI* pCmdUI) { //TODO:Add your command update UI handler code here pCmdUI->SetCheck((m_wndStatusBar.GetBarStyle()&WS_VISIBLE)!=0); } STEP 4: Then in the MainFrm.cpp file make the changes in the original frame of statusbar as followsBEGIN_MESSAGE_MAP(CMainFrame,CFrameWnd) //{AFX_MSG_MAP(CMainFrame) ON_WM_CREATE() ON_COMMAND(ID_VIEW_STATUS_BAR,OnViewStatusBar) ON_UPDATE_COMMAND_ UI(ID_VIEW_STATUS_BAR,OnUpdateViewStatusBar) //}AFX_MSG_MAP() END_MESSAGE_MAP() static UINT indicators[]= {
51

REG.NO:

NAME:

ID_SEPARATOR, ID_SEPARATOR, ID_INDICATOR_NUM, }; ///////////////////////////////////////////////////////////////////////////////////// //CMainFrame construction/destruction STEP 5: Then in the MainFrm.cpp file itself just following code if(!m_wndStatusBar.Create(this)|| !m_wndStatusBar.SetIndicators(indicators,sizeof(indicators)/size(UINT))) { TRACE0(Failed to create statusbar\n); Return -1; } With if(!m_wndStausBar.Create(this, WS_CHILD|WS_VISIBLE|CBRS_BOTTOM,ID_MYSTATUSBAR)|| !m_wndStatusBar.SetIndicators(indicators,sizeof(indicators)/sizeof(UINT))) { TRACE0(Failed to create status bar\n); Return -1; } STEP 6: Open the MainFrm.h file and make the variable m_wndStatusBar as public insted of protected. public: CStatusBar m_wndStatusBar; STEP 7: Update OnDraw function as followsvoid CStatusBarDemoView::OnDraw(CDC* pDC) { //TODO: add draw ccode for native data here pDC->TextOut(10,10,Look at the StatusBar at the bottom); } Then obtain the class wizard and add the message WM_MOUSEMOVE for the class CStatusBarDemoView. Then on the message handler add the following code//CStatusBarDemoView message handlers void CStatusBarDemoView::OnMouseMove(UINT nFlags,Cpoint point) { //TODO: add your message handler code here and/or call default CString input_msg; CMainFrame * ptr_Frame=(CMainFrame*)AfxGetApp()->m_pMainWnd; CStatusBar* ptr_Status=&ptr_Frame->m_wndStatusBar; ptr_Status->SetPaneText(0,Yes, This is my StatusBar); if(ptr_Status) {
52

REG.NO:

NAME:

input_msg.Format(x=%d,y=%d,point.x,point.y); ptr_Status->SetPaneText(1,input_msg); } CView::OnMouseMove(nFlags,point); } STEP 8: Include the header file MainFrm.h in the StatusDemoView.cpp file at the top using following statement #include MainFrm.h STEP 9: Build the application and following output can be obtained.

OUTPUT:

RESULT: Thus the above program has been executed successfully and output is verified. Ex.No:10(a)

SPLITTER-STATIC SPLITTER WINDOW


53

REG.NO:

NAME:

CREATION
Date:

AIM: To write a VC++ program to create a static splitter window. PROCEDURE: STEP 1: Start VC++ program. Select File->New ->MFC AppWizard(exe).Give the project name as staticsplitter .Then select the single Document Interfaceoption. STEP 2: Then click Next button by accepting all the Default values for further steps. Make sure that at Step 4,Use Split windows Check box is unchecked

STEP 3: Open theMainfrm.h file. Add the variables for Splitter window and for initialization flag. class CMainFrame : public CFrameWnd { // Attributes public: CSplitterWnd m_MySplitterWnd; BOOL m_flag; STEP 4: Then open the Mainfrm,cpp file and set the initial value of m_flag to FALSE in the constructor. // CMainFrame construction/destruction CMainFrame::CMainFrame()
54

REG.NO:

NAME:

{ }

// TODO: add member initialization code here m_flag=FALSE;

STEP 5:Then add message for the class CMainFrame as OnCreateClient which can be then edited as below. // CMainFrame message handlers BOOL CMainFrame:OnCreateClient(LPCREATESTRUCT lpcs,CCreateContext* pContext) { CRect m_rect; GetClientRect(m_rect); if(!m_MySplitterWnd.CreateStatic(this,1,2)) { MessageBox("Error in Creating Splitter Window"); return FALSE; } if(! m_MySplitterWnd.CreateView(0,0,RUNTIME_CLASS(CstaticsplitterView),CSize(m_rect.Width( )/2,m_rect.Height()),pContext)) { MessagBox("Error in creating splitter window"); return FALSE; } if(! m_MySplitterWnd.CreateView(0,1,RUNTIME_CLASS(CstaticsplitterView),CSize(m_rect.Width( )/2,m_rect.Height()),pContext)) { MessageBox("Error in creating Splitter window"); return FALSE; } m_flag=TRUE; return TRUE; } In the above code by CreateStatic the splitter. The parameters to this call are this is pointer to the parent window, 1 and 2 indicates number of rows and number of columns. Then we have created the views for these splitter using CreateView function.It require the RUNTIME_CLASS CstaticsplitterView. Therefore include the staticsplitterView.h file in the MainFrm.cpp file as below. // MainFrm.cpp : implementation of the CMainFrame class #include "stdafx.h" #include "staticsplitter.h" #include "MainFrm.h" #include "staticsplitter.h"
55

REG.NO:

NAME:

Now include staticsplitterDoc.h file in the staticsplitterView.h file as shown below#include "ataticsplitterDoc.h" #endif // _MSC_VER > 1000 STEP 6: Just build this application and you will get following output.

STEP 7: We can resize the splitter window by adding the message WM_SIZE on the CMainFrame class. Just involve the ClassWizard and add the message WM_SIZE for the CMainFrame class. Edit the code ass follows void CMainFrame::OnSize(UINT nType, int cx, int cy) { CFrameWnd::OnSize(nType, cx, cy); // TODO: Add your message handler code here CRect m_rect; GetWindowRect(&m_rect); if(m_flag&&nType!=SIZE_MINIMIZED) { m_MySplitterWnd.SetRowInfo(0,cy,0); m_MySplitterWnd.SetColumnInfo(0,m_rect.Width()/2,50); m_MySplitterWnd.SetColumnInfo(1,m_rect.Width()/2,50); m_MySplitterWnd.RecalcLayout(); } } STEP 8: Then open the staticsplitterView.cpp file and modify the draw function as

56

REG.NO:

NAME:

// CstaticsplitterView drawing void CstaticsplitterView::OnDraw(CDC* pDC) { CstaticsplitterDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); // TODO: add draw code for native data here pDC->TextOut(10,10,"Window is divided into 2 columns"); } STEP 9: Build the application and you will get the following output. OUTPUT:

RESULT: Thus the above program has been executed successfully and output is verified
57

REG.NO:

NAME:

Ex.No:10(b) Date: AIM:

SPLITTER-DYNAMIC SPLITTER WINDOW CREATION

To write a VC++ program for creating a dynamic splitter window. PROCEDURE: STEP 1: Start VC++ program. Select file->New ->MFC AppWizard(exe).Give the project name as ss .Then select the single Document Interfaceoption. Click Next button. Follow the steps wand step3 by accepting the default values. STEP 2: At step 4, click on the Advanced button and click the Windows Style. Just check the Use split Window.

Then click the close button. Then continue further by accepting the default values to generate the skeleton code. STEP 3: Notice that the splitter window can be created in the MainFrm.cppfile on OnCreateClient Message as BOOL CMainFrame::OnCreateClient(LPCREATESTRUCT /*lpcs*/, CCreateContext* pContext) { return m_wndSplitter.Create(this, 2, 2, // TODO: adjust the number of rows, columns CSize(10, 10), // TODO: adjust the minimum pane size pContext); }
58

REG.NO:

NAME:

STEP 4: Edit the draw function in the ssView.cpp as followsvoid CSsView::OnDraw(CDC* pDC) { CSsDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); // TODO: add draw code for native data here pDC->TextOut(20,20,"Hello"); } STEP 5: Build the application and you will get the following output. OUTPUT:

RESULT: Thus the above program has been executed successfully and output is verified.

59

REG.NO:

NAME:

Ex.No: 11 Date: AIM: To create the windows common dialog using MFC AppWizard(exe). PROCEDURE: STEP1:Create the MFC application using the MFC application(exe) option.Give project name(cdialog) .Select the Dialog based radio button.Then click finish.Make the design as follows using static text controls,edit box conmtrols,button controls.

WINDOWS COMMON DIALOG

STEP 2: Then add member variables for the three edit boxes as m_name, m_designation, m_doj of the data type CString .Add the message BN_CLICKED for the three buttons. STEP 3: Open the source file cdialogdlg.cpp in which the CFile controls in used. CCdialogDlg::CCdialogDlg(CWnd* pParent /*=NULL*/) : CDialog(CCdialogDlg::IDD, pParent) { //{{AFX_DATA_INIT(CCdialogDlg) m_name = _T(""); m_designation = _T(""); m_doj = _T(""); //}} } BEGIN_MESSAGE_MAP(CCdialogDlg, CDialog) ON_BN_CLICKED(IDC_BUTTON1, OnButton1) ON_BN_CLICKED(IDC_BUTTON2, OnButton2) ON_BN_CLICKED(IDC_BUTTON3, OnButton3)

60

REG.NO:

NAME:

//}}AFX_MSG_MAP END_MESSAGE_MAP() void CCdialogDlg::OnButton1() { // TODO: Add your control notification handler code here this->UpdateData(); CFile fp; char fs[]={"Txt Files(*.txt)|All Files(*.*)|*.*||"}; CFileDialog myfile(FALSE,"txt",NULL,0,fs); if(myfile.DoModal()==IDOK) { fp.Open(myfile.GetFileName(),CFile::modeCreate|CFile::modeWrite); CArchive myarch(&fp,CArchive::store); myarch<<m_name<<m_designation<<m_doj; myarch.Close(); } else return; fp.Close(); } void CCdialogDlg::OnButton2() { // TODO: Add your control notification handler code here this->UpdateData(); CFile fp; char fs[]={"Txt Files(*.txt)|All Files(*.*)|*.*||"}; CFileDialog myfile(TRUE,"txt",NULL,0,fs); if(myfile.DoModal()==IDOK) { if(fp.Open(myfile.GetFileName(),CFile::modeRead)==FALSE) return; CArchive myarch(&fp,CArchive::load); myarch>>m_name>>m_designation>>m_doj; myarch.Close(); } else return; fp.Close(); this->UpdateData(FALSE); } void CCdialogDlg::OnButton3() { // TODO: Add your control notification handler code here MessageBox("Good Bye!!!"); exit(0);}
61

REG.NO:

NAME:

OUTPUT:

SAVE

RESULT: Thus the above program has been executed successfully and output is verified. Ex.No:12(a)
62

REG.NO:

NAME:

Date:

DYNAMIC LINK LIBRARY(USING MFC EXTENSION)

AIM: To create a DLL using MFC extension. PROCEDURE: STEP 1: Start VC++.Select File->New. Then Select MFC AppWizard(dll) and give the project name as dlldemo1.Click OK.

Then select MFC Extension DLL (using shared MFC DLL).Then click Next button and then click Finish to get the skeleton code.

STEP2: Now click on the ClassView and right click on dlldemo1class in order to add New class.

63

REG.NO:

NAME:

Select Generic class to add new class named dlldemo1class as follows:

STEP3: Add the function for conversion of a USA Dollar to Indian rupees.Just right click on dollardll in the ClassView and select Add member function and give the details of function conversion as follows

Then add the code for the member function as follows in dollarclass.cpp file
64

REG.NO:

NAME:

dollarclass::~dollarclass() { }

double dollarclass::conversion(double a) { return a*(50.92); } STEP 4: Open the dollarclass.h and make some modification as follows. // dollarclass.h: interface for the dollarclass class. #endif // _MSC_VER > 1000 class AFX_EXT_CLASS dollarclass { public: int con(int a); double conversion(double a); dollarclass(); virtual ~dollarclass(); }; STEP 5: Save the application and build the project to generate the DLL and LIB files.dollardll.DLL and dollardll.LIB files get generated in the debug directory. Copy the dollardll.DLL file in C:Windows\System32. STEP 6: Create the client program which make use of our DLL file created for conversion. Start VC++ Select File->New .Select MFC AppWizard (exe).Give the project name as dollarclient. Select the radio button Dialog based for creating a dialog based application. STEP 7: Create the design as follows

The controls that are placed on above dialogbox are summarized as below:

65

REG.NO:

NAME:

Control Edit Box Edit Box Button Static Text Static Text Static Text

Object ID IDC_EDIT1 IDC_EDIT2 IDC_BUTTON1 IDC_STATIC IDC_STATIC IDC_STATIC

Caption Conversion Dollar to Rupee Conversion Enter the amount in dollar Indian Ruppes

STEP 8: Click Project->Settings then click Link tab. Enter the LIB file name in the Object/library modules edit box as follows.

STEP 9: Copy the header file dollarclass.h in your projects folder dollarclient. STEP 10: Go to dollarclient, Click on the File view. Open the file StdAfx.h and include the header file. #include <afxcmn.h> // MFC support for Windows Common Controls #endif // _AFX_NO_AFXCMN_SUPPORT #include "dollarclass.h" //{{AFX_INSERT_LOCATION}} STEP 11: Open the header file dollarclientDlg.h class CDollarclientDlg : public CDialog{ // Construction public: CDollarclientDlg(CWnd* pParent = NULL); // standard constructor dollarclass obj; double x; // Dialog Data STEP 12: Invoke the class wizard by pressing ctrl+w. Add the message BN_CLICKED for the object IDC_BUTTON1 for the Cdollarclientdlg and edit the code as follows; void CDollarclientDlg::OnButton1()
66

REG.NO:

NAME:

// TODO: Add your control notification handler code here x=GetDlgItemInt(IDC_EDIT1); double y=obj.conversion(x); int z=int(y); SetDlgItemInt(IDC_EDIT2,z,TRUE);

} void CDollarclientDlg::OnButton2() { // TODO: Add your control notification handler code here SetDlgItemInt(IDC_EDIT1,0); SetDlgItemInt(IDC_EDIT2,0); } STEP 12: Build the application and execute. OUTPUT:

RESULT: Thus the above program has been executed successfully and output is verified.

67

REG.NO:

NAME:

Ex.No:12(b) Date:

DYNAMIC LINK LIBRARY(REGULAR DLL USING SHARED MFC)

AIM: To create a DLL using regular DLL using shared MFC PROCEDURE: STEP 1: Start VC++.Select File->New. Then Select MFC AppWizard(dll) and give the project name as dlldemo1.Click OK.

Then select MFC Extension DLL (using shared MFC DLL).Then click Next button and then click Finish to get the skeleton code.

68

REG.NO:

NAME:

STEP2: Now click on the ClassView and right click on dlldemo1class in order to add New Class.

Select Generic class to add new class named dlldemo1class as follows:

STEP3: Add the function for multiplying two numbers name it as add. Right click on dlldemo1class in the ClassView and select add member function and give the details of function add as follows. Add member function for subtraction, multiplication, division

69

REG.NO:

NAME:

Then add the code for the member function as follows in dlldemo1class.cpp file int dlldemo1class::add(int a, int b) { return a+b; } int dlldemo1class::sub(int a, int b) { return a-b; } int dlldemo1class::mul(int a, int b) { return a*b; } int dlldemo1class::div(int a, int b) { return a/b; } STEP 4 :Now go to File view and open the file dlldemo1class.h and prefix _declspec(dllexport) to all the function as follows. class dlldemo1class { public: _declspec(dllexport)int div(int a,int b); _declspec(dllexport)int mul(int a,int b); _declspec(dllexport)int sub(int a,int b); _declspec(dllexport)int add(int a,int b); _declspec(dllexport)dlldemo1class(); _declspec(dllexport)virtual ~dlldemo1class(); }; STEP5: Build the application to generate the dll file.Note that in the debug folder of your projects folder the dlldemo1.dll and dlldemo1.lib files gets generated. STEP 6: Now create a client application program which will make use of your dll file. Start VC++.Select MFC AppWizard(exe).Give the project name as dlldemotest1.Select theDialog based option. Click Next button and give Finish button to get the skeleton code. STEP7: Select the Resource view .click the Dialog folder, and design the dialog box as follows.

70

REG.NO:

NAME:

In the dialog box following controls are placed. Control EditBox EditBox Button Button Button Button Button Static Text Static Text Object ID IDC_EDIT1 IDC_EDIT2 IDC_BUTTON1 IDC_BUTTON2 IDC_BUTTON3 IDC_BUTTON4 IDC_BUTTON5 IDC_STATIC IDC_STATIC Caption Addition Subtraction Multiplication Division Cancel Dll Demo program for addition and multiplication of two numbers. Enter two numbers

STEP 8: Invoke the class wizard and add the member variables of integer type for the edit boxes as

STEP 9: Open the file dlldemotest1.h and edit it as follows // dlldemotest1Dlg.h : header file #include "D:\dlldemo1\dlldemo1class.h" class CDlldemotest1Dlg : public CDialog
71

REG.NO:

NAME:

{ // Construction dlldemo1class obj1; public: CDlldemotest1Dlg(CWnd* pParent = NULL); STEP 10: Get the class wizard and for the IDC_BUTTON1, IDC_BUTTON2, IDC_BUTTON3, IDC_BUTTON4, IDC_BUTTON5 add the messages BN_CLICKED on the class Cdlldemotest1dlg,edit the code as follows void CDlldemotest1Dlg::OnButton1() { // TODO: Add your control notification handler code here UpdateData(TRUE); int result=obj1.add(m_x,m_y); CString msg; msg.Format("%d",result); MessageBox(msg,"result",MB_OK); } void CDlldemotest1Dlg::OnButton2() { // TODO: Add your control notification handler code here UpdateData(TRUE); int result=obj1.sub(m_x,m_y); CString msg; msg.Format("%d",result); MessageBox(msg,"result",MB_OK); } void CDlldemotest1Dlg::OnButton3() { // TODO: Add your control notification handler code here UpdateData(TRUE); int result=obj1.mul(m_x,m_y); CString msg; msg.Format("%d",result); MessageBox(msg,"result",MB_OK); } void CDlldemotest1Dlg::OnButton4() { // TODO: Add your control notification handler code here UpdateData(TRUE); int result=obj1.div(m_x,m_y); CString msg; msg.Format("%d",result); MessageBox(msg,"result",MB_OK); } void CDlldemotest1Dlg::OnButton5() { // TODO: Add your control notification handler code here CDialog::OnCancel(); }
72

REG.NO:

NAME:

STEP 11:Now establish the connection between the client program and the dll. Select Project->Settings. Select the link tab and include the link tab and include the lib file in the object/library modules as follows:

Click ok button. STEP 12: Copy the dlldemo1.dll file to dlldemodemo\debug folder.and copy the dlldemo1.dll into windows/system32 folder. STEP 13: Build the application. OUTPUT:

RESULT: Thus the above program has been successfully executed and output is verified.

73

REG.NO:

NAME:

Ex.No:12(c) Date:

DYNAMIC LINK LIBRARY(REGULAR DLL USING STATICALLY LINKED)

AIM: To create the DLL using regular DLL with MFC statically linked option. PROCEDURE: STEP 1: Start vc++.select file->New.then select the option MFC APPWizard(dll) and give the project name as staticdlldemo. STEP 2: Select the radio button for Regular DLL with MFC statically linked as follows

Click the finish button to get the skeleton code. STEP 3: Go to workspace window and clik on the File view.Add one empty .cpp file and the.h file.Name them as mydll.cpp and mydll.h respectively. Then add the code in mydll.cpp as follows

Write the mydll.h file as follows


74

REG.NO:

NAME:

extern "C" _declspec(dllexport)double compute_interest(int p,int n,int r); extern "C" _declspec(dllexport)double compute_interest1(int p,int n,int r) ; Thus we have created separate files for DLL functionality. STEP 4: Build the application and the staticdlldemo.dll and staticdlldemo.lib file will be generatedin the Debug folder.Close the DLL program. STEP 5: Now create a client application program which will make use of your DLL files. Start vc++.select MFC AppWizard(exe).Give the project name as staticdlldemotest.select the Dialog based option.Click Next button and finally Finishbutton to get the skeleton code. STEP 6: Select the Resource View from workspace and click the Dialog folder,delete the OK button and design the dialog box as follows

The controls that are placed in the dialog box are summerised as followsControls Object ID Caption Edit Box IDC_EDIT1 Edit Box IDC_EDIT2 Edit Box IDC_EDIT3 Edit Box IDC_EDIT4 Edit Box IDC_EDIT5 Button IDC_Button1 Compute Button IDC_Button2 Compute1 Static Text IDC_STATIC Simple and compound interest Static Text IDC_STATIC Enter the Amount Static Text IDC_STATIC Enter the year Static Text IDC_STATIC Enter the interest Static Text IDC_STATIC Result(in Rs.): STEP 7: Get the class wizard and add the member variable for all the Edit boxes as follows

75

REG.NO:

NAME:

Note that the data type of first three edit boxes is integer and the data type of forth edit box is CString. Click OK button. STEP 8:Now click the FileView tab,and right click on the Header Files folder to add the header file mydll.h which we have created in step3.

Then open the file staticdlldemotestdlg.cpp and include the header file as follows// staticdlldemotestDlg.cpp : implementation file #include "stdafx.h" #include "staticdlldemotest.h" #include "staticdlldemotestDlg.h" #include "F:\staticdlldemo\mydll.h" #ifdef _DEBUG STEP 9: Now get the ClassWizard and add the message BN_CLICKED for IDC_BUTTON1 for the class CStaticdlldemotestddlg. Edit the code for this message handler as followsvoid CStaticdlldemotestDlg::OnButton1() { // TODO: Add your control notification handler code here CString msg;
76

REG.NO:

NAME:

UpdateData(TRUE); double result=compute_interest(m_p,m_n,m_r); msg.Format ("%f",result); m_interest=msg; UpdateData(FALSE); } void CStaticdlldemotestDlg::OnButton2() { // TODO: Add your control notification handler code here CString msg; UpdateData(TRUE); double result=compute_interest1(m_p,m_n,m_r); msg.Format ("%f",result); m_interest=msg; UpdateData(FALSE); } STEP 10: To establish the connection of client program with out DLL click the Menu item Project->Settings.select the link tab and include the LIB as follows-

STEP 11: Copy the staticdlldemo.dll file(generated in step 4)to the folder \staticdlldemotest\dedug STEP12: Build the application, execute it and you will get the following output.

OUTPUT:
77

REG.NO:

NAME:

RESULT: Thus the above program has been successfully executed and output is verified.

78

REG.NO:

NAME:

Ex.No: 13(a) Date: AIM:

CREATION OF ACTIVEX CONTROL

To write a visual C++ program for creating ActiveX control. PROCEDURE: STEP 1: Start VC++. Select File->New->MFCActiveXControlWizard. Type the project name ActiveXDemo in the Project name window->OK.

STEP 2: Then accept the default option and click the Next button on the window appearing as follows-

STEP 3: Then select the features for your ActiveX. Check the checkboxes as shown below-> click the Finish button.

79

REG.NO:

NAME:

The skeleton code gets generated as follows.

STEP 4: If we click on the ClassView of the project workspace then we can see that following classes gets generated by the Control Wizard.

80

REG.NO:

NAME:

STEP 5: Now click on Tools->ActiveX Control Test Container. This is a Test Container normally used for newly created ActiveX Control. Go to Edit->Insert New Control.

And the list of registered ActiveX components/controls will appear as follows. Just select our control ActiveXDemo control by clicking OK button.

81

REG.NO:

NAME:

Following output will be displayed. Note that by the default the Control Wizard as follows. We can move or resize this control.

We have seen by default the Control Wizard generates the elliptical control. We can change its shape, size and we can add some events to it. In this selection we will create an ActiveX Control whose shape is rectangular. It is Blue in color. And if we click left mouse button over it will display some string as MyControl. STEP 6: Now invoke the Class Wizard. Click on the Automation tab. Ensure that the class name is CActiveXDemoCtrl. Click Add Property method.

Now click the Add Property button. From the combo box of External name select the BackColor property. Ensure that for the implementation the Stock radio button is clicked. Then click the OK button as shown below82

REG.NO:

NAME:

Then add other function by clicking the Add Property button, type the External name as MyString give the type as OLE_COLOR. Give the name of some variable as m_mystring. Set the Implementation option as Member Variable.

Then click OK button. The ClassWizard will then display the list of newly added properties.

83

REG.NO:

NAME:

STEP 7: Now click the Message Maps tab on the ClassWizard. And add the messages for WM_LBUTTONDOWN and WM_LBUTTONUP.

STEP 8: Now Edit the code in the ActiveXDemoCtl.cpp file STEP 9: Now save the application and rebuild it. You can see this ActiveX control by invoking the ActiveX Control Test Container. (As we did in STEP 5) Just click the button on this control and you can see the string MyControl getting displayed. // ActivexcontCtl.cpp : // CActivexcontCtrl::OnDraw - Drawing function void CActivexcontCtrl::OnDraw( CDC* pdc, const CRect& rcBounds, const CRect& rcInvalid) { // TODO: Replace the following code with your own drawing code. CBrush *pmybrush; CBrush bluebrush; CPen *pmypen; CPen bluepen; pdc->FillRect(rcBounds, CBrush::FromHandle((HBRUSH)GetStockObject(WHITE_BRUSH))); bluepen.CreatePen(PS_SOLID,2,RGB(0,0,255)); pmypen=(CPen*)pdc->SelectObject(&bluepen); bluebrush.CreateSolidBrush(RGB(0,0,255)); pmybrush=(CBrush*)pdc->SelectObject(&bluebrush); pdc->Rectangle(rcBounds); pdc->SelectObject(pmypen); pdc->SelectObject(pmybrush); } void CActivexcontCtrl::OnMystringChanged(CDC* pdc) { // TODO: Add notification handler codeCRect m_rect; CRect m_rect; pdc->SetBkMode(TRANSPARENT); GetClientRect(m_rect);
84

REG.NO:

NAME:

pdc->Rectangle(m_rect); pdc->TextOut((m_rect.left+m_rect.right-80)/2,(m_rect.bottom+m_rect.top5)/2,"my activex control"); SetModifiedFlag(); } void CActivexcontCtrl::OnLButtonDown(UINT nFlags, CPoint point) { // TODO: Add your message handler code here and/or call default CDC *pdc; pdc=GetDC(); OnMystringChanged(pdc); ReleaseDC(pdc); COleControl::OnLButtonDown(nFlags, point); } void CActivexcontCtrl::OnLButtonUp(UINT nFlags, CPoint point) { // TODO: Add your message handler code here and/or call default InvalidateControl(); COleControl::OnLButtonUp(nFlags, point); } OUTPUT:

RESULT: Thus the above program has been successfully executed and verified.
85

REG.NO:

NAME:

Ex.No: 13(b) Date: AIM:

CALENDAR CONTROL USING ACTIVEX CONTROLS

To write a visual C++ program for Calendar Control using ActiveX Controls. PROCEDURE: STEP 1: Start VC++ Click New on the menu bar and Select the MFC AppWizard(exe) option. Give the project name as Calendar Click OK button.

. STEP 2: Now select the Dialog based radio button and click Next button, Accept the default values and finally click the finish button and generated skeleton code.

STEP 3: Now to install the Calendar control on the Control tool box, select the Project->Add To Project->Components and Controls.
86

REG.NO:

NAME:

Then click Insert button to insert the control. Answer ok for inserting the control. Then go to Control toolbox and you can see the control for calendar appears on the toolbox. Just drag it and place on the dialog box. Design the dialog box as follows. Various controls that are placed on the dialog box are summarized as below. Control Calendar control 8.0 or 11.0 EditBox EditBox EditBox StaticBox StaticBox StaticBox StaticBox Button Button Button Button Button Button ObjectID IDC_CALENDAR1 IDC_EDIT_DAY IDC_EDIT_MONTH IDC_EDIT_YEAR IDC_STATIC IDC_STATIC IDC_STATIC IDC_STATIC IDC_SELECT IDC_TODAY IDC_NEXT_YEAR IDC_NEXT_MONTH IDC_PREV_YEAR IDC_PREV_MONTH Caption

dd mm yyyy Date Select Today >> > << <

87

REG.NO:

NAME:

STEP 4: Now add the variables and messages for these controls.Press Ctrl+W. Control ObjectID Variable VariableType EditBox IDC_EDIT_DAY m_day Short EditBox IDC_EDIT_MONTH m_month Short EditBox IDC_EDIT_YEAR m_year Short Calendar control IDC_CALENDAR1 m_mycalendar CCalendar ObjectID Message Message handler IDC_SELECT BN_CLICKED OnSelect IDC_TODAY BN_CLICKED OnToday IDC_NEXT_YEAR BN_CLICKED OnNextYear IDC_NEXT_MONTH BN_CLICKED OnNextMonth IDC_PREV_YEAR BN_CLICKED OnPrevYear IDC_PREV_MONTH BN_CLICKED OnPrevMonth IDC_CALENDAR1 Click OnClickCalendar1 IDC_CALENDAR1 AfterUpdate OnAfterUpdateCalendar1 STEP5: Now open the file CalendarDlg.cpp and edit the code for message handler function as followsBOOL CCaledarDlg::OnInitDialog() { // TODO: Add extra initialization here UpdateData(TRUE); m_day = m_mycalendar.GetDay(); m_month = m_mycalendar.GetMonth(); m_year = m_mycalendar.GetYear(); UpdateData(FALSE); return TRUE; // return TRUE unless you set the focus to a control } void CCaledarDlg::OnSelect() { // TODO: Add your control notification handler code here CDataExchange dx(this,TRUE); DDX_Text(&dx,IDC_EDIT_DAY,m_day); DDX_Text(&dx,IDC_EDIT_MONTH,m_month); DDX_Text(&dx,IDC_EDIT_YEAR,m_year); m_mycalendar.SetDay(m_day); m_mycalendar.SetMonth(m_month); m_mycalendar.SetYear(m_year); } void CCaledarDlg::OnToday() { // TODO: Add your control notification handler code here m_mycalendar.Today() }
88

REG.NO:

NAME:

void CCaledarDlg::OnPrevMonth() { // TODO: Add your control notification handler code here m_mycalendar.PreviousMonth(); } void CCaledarDlg::OnPrevYear() { // TODO: Add your control notification handler code here m_mycalendar.PreviousYear(); } void CCaledarDlg::OnNextYear() { // TODO: Add your control notification handler code here m_mycalendar.NextYear(); } void CCaledarDlg::OnNextMonth() { // TODO: Add your control notification handler code here m_mycalendar.NextMonth(); } void CCaledarDlg::OnClickCalendar1() { // TODO: Add your control notification handler code here UpdateData(TRUE); m_day = m_mycalendar.GetDay(); m_month = m_mycalendar.GetMonth(); m_year = m_mycalendar.GetYear(); UpdateData(FALSE); } void CCaledarDlg::OnAfterUpdateCalendar1() { // TODO: Add your control notification handler code here UpdateData(TRUE); m_day = m_mycalendar.GetDay(); m_month = m_mycalendar.GetMonth(); m_year = m_mycalendar.GetYear(); UpdateData(FALSE); } OUTPUT:

RESULT: Thus the above program has been successfully executed and verified.
89

REG.NO:

NAME:

Ex.No: 13(c) Date: AIM: To write a visual C++ program to Create ActiveX Control at RunTime. PROCEDURE: STEP 1: Start VC++.Select the option MFC Appwizard(exe).Give the project name as RunTimeActiveX.Click OK button STEP 2: Then go to menu.And click Project->Add to Project->Components and Control Then click on the Registered ActiveX controls folder.Select the control Microsoft WebBrowser as shown belowACTIVEX CONTROL AT RUNTIME

Click Insert button to insert the control.Then the Class name for the selected control will appear as follows.

Click OK Button to accept the default class for web browser.


90

REG.NO:

NAME:

STEP 3:Now click on the ClassView in the project workspace.Right click on the CRunTimeActiveXView class to add the variable for it.Add two variable as follows

STEP 4: Then include the default header file of the webbrowser control in the RunTimeActiveXView.h file. STEP 5: Now Add two Resource symbols using the menu item View->Resource Symbols ie ID_BROWSER_FIND and ID_BROWSER_RESULT.

Step 6: Now its time to set the name of the website which you want to get displayed.Open the file RunTimeActivXView.h and the following arry of characters. // RactivexView.h : interface of the CRactivexView class private: static const char WebSite[]; CWebBrowser2 m_result; CWebBrowser2 m_find; }; STEP 6: Open the source file RactivexView.cpp and add the name of the website just
91

REG.NO:

NAME:

outside the OnDraw function as follows. // CRactivexView drawing void CRactivexView::OnDraw(CDC* pDC) { // TODO: add draw code for native data here } const char CRactivexView::WebSite[]="http://www.google.com"; STEP 7:Now for the class CRunTimeActiveXView add two messages handlers WM_CREATE and WM_SIZE and edit code as follows. // CRactivexView message handlers int CRactivexView::OnCreate(LPCREATESTRUCT lpCreateStruct) { if (CView::OnCreate(lpCreateStruct) == -1) return -1; // TODO: Add your specialized creation code here DWORD dwstyle=WS_VISIBLE|WS_CHILD; if(m_find.Create(NULL,dwstyle,CRect(0,0,150,150),this,ID_BROWSER_FIND)==0) { AfxMessageBox("unable create control"); return -1; } m_find.Navigate(WebSite,NULL,NULL,NULL,NULL); if(m_result.Create(NULL,dwstyle,CRect(0,0,150,150),this,ID_BROWSER_RESULT)==0) { AfxMessageBox("unable create control"); return -1; } m_result.GoHome(); return 0; } void CRactivexView::OnSize(UINT nType, int cx, int cy) { // TODO: Add your message handler code here CRect m_rect; GetClientRect(m_rect); CRect browserRect(m_rect); browserRect.left=0; browserRect.top=0; browserRect.right=500; browserRect.bottom=500; m_find.SetWidth(800); m_result.SetWidth(500); m_find.SetHeight(800); m_result.SetHeight(800); m_find.UpdateWindow();
92

REG.NO:

NAME:

m_result.UpdateWindow(); } STEP 8: Write the coding on the RactiveXView.h file protected: afx_msg void OnBrowsing(LPCTSTR URL,long flags,LPCTSTR TargetFrameName,VARIANT FAR* PostData,LPCTSTR Header,BOOL FAR* Cancel); DECLARE_EVENTSINK_MAP() STEP 9:Edit the code on the message handler RactivexView.cpp BEGIN_EVENTSINK_MAP(CRactivexView,CView) ON_EVENT(CRactivexView,ID_BROWSER_FIND,100,OnBrowsing,VTS_BSTR VTS_I4 VTS_BSTR VTS_PVARIANT VTS_BSTR VTS_PBOOL) END_EVENTSINK_MAP() Then edit the code for message handlers void CRactivexView::OnBrowsing(LPCTSTR URL, long flags, LPCTSTR TargetFrameName, VARIANT *PostData, LPCTSTR Header, BOOL *Cancel) { if(!strnicmp(URL,WebSite,strlen(WebSite))) { return; } m_result.Navigate(URL,NULL,NULL,PostData,NULL); *Cancel=TRUE; } STEP 10:Write the coding for RactivexView.h private: static const char WebSite[]; CWebBrowser2 m_result; CWebBrowser2 m_find; };

OUTPUT:
93

REG.NO:

NAME:

94

REG.NO:

NAME:

RESULT: Thus the above program has been executed successfully and output is verified.

95

REG.NO:

NAME:

Ex.No:14 Date:

OBJECT LINKING & EMBEDDING(OLE)

AIM: To write a VC++ program to demonstrate object linking and embedding. PROCEDURE: STEP 1: Start VC++.Select the option MFC Application(exe) and give the project name as OLEDemo. Click OK button.

STEP 2: Then select the Single Document Interface. And accept the default value at the step 2 By clicking the Next button. STEP 3: Select the Mini-server option.

96

REG.NO:

NAME:

STEP 4: Then select the Next button by accepting all the default values from step 4 to 6. Finally click Finish button and get the skeleton code ready . STEP 5: Click the ClassView in the workspace and add the member variable m_str of CString type in the public access mode.Check presence of following code is in OLEDemoDoc.h file. OLEDemoDoc.h: // Implementation public: CString m_str; virtual ~COLEDemoDoc(); STEP 6: Now add one dialog box. And design it as follows:

Now invoke a ClassWizard. First of all it will ask you to create a new class for the added dialog box. Click OK for adding a new class. Then set the name of this dialog class as CMyStrDialog. We have placed following components on the dialog box Control Edit Box Static Text Object ID IDC_EDIT1 IDC_STATIC (Caption is Enter Something Here:)

Now for the Edit Box IDC_EDIT1 add the variable as m_str which is of the CString type.Then open the OLEDemoDoc.cpp file and edit it as follows: // OLEDemoDoc.cpp : implementation of the COLEDemoDoc class #include "stdafx.h" #include "OLEDemo.h" #include "SrvrItem.h" #include "MyStrDialog.h"
97

REG.NO:

NAME:

STEP 6: Now we will edit menu bar.By default we get the three IDs for Menu bars IDR_MAINFRAME,IDR_SRVR_EMBEDDED and ID_SRVR_INPLACE

Add one menu item Change. Set the same ID for all the Change menu items as ID_CHANGE.Then add the message COMMAND for the Change menu item.

98

REG.NO:

NAME:

Then edit code on the message handler OnChange() as follows: void COLEDemoDoc::OnChange() { // TODO: Add your command handler code here CMyStrDialog dlg; dlg.m_str=m_str; if(dlg.DoModal()==IDOK) { m_str=dlg.m_str; UpdateAllViews(NULL); UpdateAllItems(NULL); SetModifiedFlag(); } } STEP 8: Then in the OLEDemoDoc.cpp file edit the NewDocument function as follows: BOOL COLEDemoDoc::OnNewDocument() { m_str="Hello from Document"; if (!COleServerDoc::OnNewDocument()) return FALSE; // TODO: add reinitialization code here // (SDI documents will reuse this document) return TRUE; } STEP 9: Now we will override the function OnPrepareDC of COLEDemoView by adding this Message handler function and then editing it as follows: void COLEDemoView::OnPrepareDC(CDC* pDC, CPrintInfo* pInfo) { // TODO: Add your specialized code here and/or call the base class pDC->SetMapMode(MM_HIMETRIC); } STEP 10: Now in the OLEDemoView.cpp file the OnDraw function is modified as follows: void COLEDemoView::OnDraw(CDC* pDC) { COLEDemoDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); // TODO: add draw code for native data here CFont f; f.CreateFont(-350,0,0,0,300,FALSE,FALSE,0,ANSI_CHARSET,0,0,0,0,"century"); CFont* ptrf=pDC->SelectObject(&f);
99

REG.NO:

NAME:

CRect m_rect; GetClientRect(m_rect); CSize s=m_rect.Size(); pDC->DPtoHIMETRIC(&s); pDC->Rectangle(10,10,200,200); pDC->TextOut(0,0,pDoc->m_str); pDC->SelectObject(ptrf); } STEP 11: Open the SrvrItem.cpp file and edit the OnDraw method as follows: BOOL COLEDemoSrvrItem::OnDraw(CDC* pDC, CSize& rSize) { // TODO: add drawing code here. Optionally, fill in the HIMETRIC extent. // All drawing takes place in the metafile device context (pDC). CFont f; f.CreateFont(-500,0,0,0,300,FALSE,FALSE,0,ANSI_CHARSET,0,0,0,0,"Monotype Corsiva"); CFont* ptrf=pDC->SelectObject(&f); pDC->Rectangle(10,10,200,200); pDC->TextOut(0,0,pDoc->m_str); pDC->SelectObject(ptrf); return TRUE; } STEP 12: Now open the OLEDemoDoc.cpp file and edit the serialize() function as follows: void COLEDemoDoc::Serialize(CArchive& ar) { if (ar.IsStoring()) { // TODO: add storing code here ar<<m_str; } else { // TODO: add loading code here ar>>m_str; } } STEP 13: Build and execute th application as follows by choosing Microsoft Word.

100

REG.NO:

NAME:

OUTPUT:

101

REG.NO:

NAME:

RESULT: Thus the above program has been executed successfully and output is verified.

102

REG.NO:

NAME:

Ex.No:15(a) Date: Aim:

EMPLOYEE DATABASE

To create a Visual C++ program for Employee Database application. PROCEDURE: STEP 1: Create the database Employee.accdb with the table EmpTab.

STEP 2: Then set the ODBC driver for this database. Click on the user tab and select the user data source MS Access Database.

STEP 3: Then click Add button and then select the Microsoft Access Driver(*.mdb,* .accdb). Then click Finish button.
103

REG.NO:

NAME:

STEP 4: Then give Data Source Name as Employee Database and click the select button.

And select the database Employee.accdb Then click the OK button.

104

REG.NO:

NAME:

MFC PROGRAM: STEP 1: Start VC++ Select MFC AppWizard(exe) option.Give project name as DBDemo1. Click OK button. Then Single Document Interface option and click Next button. STEP 2: At step 2 select Headers files only option.

STEP 3: From Step 3 to 5 accept the default values and simply click the Next button. At step 6 select the base class as CScrollView. Click Finish

STEP 4: Now from the Menu bar select Insert->New Class. Give the name of this class as CDBDemoSet. Select the base class for this class as CRecordset. Click OK button.Then Database option window will appear.Click on the Datasource option as ODBC and select the Employee Database. Ensure that the Recordset type is Dynaset. Click OK button. Select the database tables. Select EmpTab. OK button.

105

REG.NO:

NAME:

106

REG.NO:

NAME:

STEP 5: By Step 4 we are associating the Employee database with our application class CDBDemoSet.If we go to workspace and check the Class View we can notice the database field names are appearing as the variable names.

If we invoke the ClassWizard then for the class CDBDeomSet we can see the definitions of these variables as follows. The square bracket indicates that these data members are derived from the database.

STEP 6: The embedded recordset now can be recognized using the class CDBDemoSet. The object of this class is then declared in the CDBDemoDoc class by going to workspace window,Rightclick the Class CDBDemoDoc and Select Add Member Variable.

107

REG.NO:

NAME:

The following code will be automatically added in the DBDemoDoc.h //Implementation

public: CDBDemoSet m_str; CDBDemoSet1(CDatabase* pDatabase = NULL); DECLARE_DYNAMIC(CDBDemoSet) STEP 7:Now add the line #include DBDemoSet.h in the file DBDemoDoc.cpp file at the top. #include "stdafx.h" #include "DBDemo.h" #include "DBDemoSet.h" #include "DBDemoDoc.h" #ifdef _DEBUG STEP 8: Now we will set the pointer variable for the embedded recordset class CDBDemoSet. For that, In the workspace window, Rightclick the Class CDBDemoView and Select Add Member Variable.

The following code will be automatically added in the DBDemoView.h class CDBDemoView : public CScrollView { private: CDBDemoSet* m_ptr; }
108

REG.NO:

NAME:

Now open the DBDemoView.cpp file and edit the code of OnInitialUpdate() function as follows: void CDBDemo1View::OnDraw(CDC* pDC) { // TODO: add draw code for native data here TEXTMETRIC tm; pDC->GetTextMetrics(&tm); int len=tm.tmHeight+tm.tmExternalLeading; CPoint pt(0,0); CString str; if(m_ptr->IsBOF()) return; pDC->TextOut(pt.x,pt.y," empno name salary"); pDC->TextOut(pt.x,pt.y-len,"......................................................."); m_ptr->MoveFirst(); while(!m_ptr->IsEOF()) { str.Format("%ld",m_ptr->m_empno); pDC->TextOut(pt.x+100,pt.y+35,str); pDC->TextOut(pt.x+200,pt.y+35,m_ptr->m_empname); str.Format("%ld",m_ptr->m_salary); pDC->TextOut(pt.x+300,pt.y+35,str); pt.y+=len; m_ptr->MoveNext(); } } void CDBDemo1View::OnInitialUpdate() { CScrollView::OnInitialUpdate(); CSize sizeTotal; // TODO: calculate the total size of this view SetScrollSizes(MM_HIENGLISH,sizeTotal); m_ptr=&GetDocument()->m_obj; if(m_ptr->IsOpen()) { m_ptr->Close(); } m_ptr->Open(); sizeTotal.cx = sizeTotal.cy = 100; SetScrollSizes(MM_TEXT, sizeTotal); } STEP 12: Build the accplication and Execute it.

109

REG.NO:

NAME:

OUTPUT:

RESULT: Thus the above program has been successfully executed and verified.

110

REG.NO:

NAME:

Ex.No:15(b) Date: AIM:

STUDENT DATABASE

To create a Visual C++ program for Student database application.


PROCEDURE:

STEP 1: Create the database Student.mdb with the table StudTab.

STEP 2: Then set the ODBC driver for this database. Click on the user tab and select the user data source MS Access Database

111

REG.NO:

NAME:

STEP 3: Then click Add button and then select the Microsoft Access Driver(*.mdb). Then click Finish button.

STEP 4: Then give Data Source Name as StudentDatabase and click the select button.

And select the database Student.mdb.Then click the OK button.

STEP 5: Start VC++. Select the option MFC AppWizard (exe). Then give name to the project as Student. Then select the Single Document option and click the Next button.
112

REG.NO:

NAME:

STEP 6: Now select the option Database view with file support and click the button Data Source

STEP 7: Click the ODBC radio button and then select the database StudentDatabase. Ensure that the radio button for Dynaset is clicked. And click OK and Finish Buttons.

113

REG.NO:

NAME:

STEP 8: The default form with TODO static box will appear. Just delete that static box and design the form as follows

Control Static text Static text Static text Edit box Edit box Edit box Button Button Button Button Button Button Button Button

Object ID IDC_STATIC IDC_STATIC IDC_STATIC IDC_EDIT1 IDC_EDIT2 IDC_EDIT3 IDC_ADD IDC_DELETE IDC_UPDATE IDC_INSERTQUERY IDC_MOVEFIRST IDC_MOVELAST IDC_MOVENEXT IDC_MOVEPREVIOUS

Properties caption=Roll No caption=Name caption=Marks

caption=Add caption=Delete caption=Update caption=SQL Query INSERT Caption=Move First Caption=Move Last Caption=Move Next Caption=Move Previous

STEP 9: Invoke ClassWizard. Click on the member variable tab and for each Edit Box set the variable.

114

REG.NO:

NAME:

After setting the member variable for each editbox we can see the member variable as follows

STEP 10: For all the buttons add the BN_CLICKED message for CStudentView class. Open the DBDemoView.cpp file and edit the code for these message handlers. STEP 11: We will use a function named ExecuteSQL in the file StudentView.cpp.This function will take a string of query as a parameter. Hence onSelect() message handler we could write as in program. STEP 12: Build the application // StudentView.cpp : // CStudentView message handlers void CStudentView::OnAdd() { // TODO: Add your control notification handler code here m_pSet->AddNew(); UpdateData(TRUE); m_pSet->Update();//entry in the database if(!m_pSet->IsBOF()) m_pSet->MoveLast(); m_pSet->Requery(); UpdateData(FALSE); } void CStudentView::OnDelete() { // TODO: Add your control notification handler code here CRecordsetStatus flag; m_pSet->Delete(); m_pSet->GetStatus(flag); if(flag.m_lCurrentRecord==0) m_pSet->MoveFirst();//reached at the end and deleted
115

REG.NO:

NAME:

else m_pSet->MoveLast(); UpdateData(FALSE); } void CStudentView::OnUpdate() { // TODO: Add your control notification handler code here m_pSet->Edit(); UpdateData(TRUE); m_pSet->Update(); } void CStudentView::OnInsert() { // TODO: Add your control notification handler code here try { m_pSet->m_pDatabase->BeginTrans(); m_pSet->m_pDatabase->ExecuteSQL("INSERT INTO studtab VALUES(106,'Krish',89)"); if(m_pSet->m_pDatabase->CommitTrans()) TRACE("Transaction done"); else TRACE("Error"); } catch(CDBException *pEX) { pEX->ReportError(); m_pSet->m_pDatabase->Rollback(); } } void CStudentView::OnMoveFirst() { // TODO: Add your control notification handler code here m_pSet->MoveFirst(); UpdateData(FALSE); MessageBox("The record is MoveFirst"); } void CStudentView::OnMovePrev() { // TODO: Add your control notification handler code here m_pSet->MovePrev(); UpdateData(FALSE); MessageBox("The record is MovePrev"); }
116

REG.NO:

NAME:

void CStudentView::OnMoveNext() { // TODO: Add your control notification handler code here m_pSet->MoveNext(); UpdateData(FALSE); MessageBox("The record is MoveNext"); } void CStudentView::OnMoveLast() { // TODO: Add your control notification handler code here m_pSet->MoveLast(); UpdateData(FALSE); MessageBox("The record is MoveLast"); } OUTPUT:

TO ADD:

117

REG.NO:

NAME:

TO DELETE:

INSERT QUERY:

TO MOVE FIRST:

TO MOVE NEXT:

118

REG.NO:

NAME:

TO MOVE PREV:

TO MOVE LAST:

RESULT: Thus Student database has been created and various operations has been build and executed successfully.

119

REG.NO:

NAME:

Ex.No:16(a) Date:

USER INTERFACE THREADS

AIM: To create an user interface thread using MFCAppwizard(exe). PROCEDURE: STEP 1: Start Visual C++, select the option MFCAppwizard(exe) and give the project name as userthread and in second wizard Select the Single Document option. Click the next buttons by accepting the default values and finally click Finish button.

STEP 2: Goto ClassView tab in workspace then right click on userthread classes and click on the New Class to create a new class.
120

REG.NO:

NAME:

STEP 3: Give the classname as CMyThread and set the BaseClass as CWinThread then Click ok button.

STEP 4: Add the massage as WM_THREADMSG, We will first define this message in StdAfx.h file.

121

REG.NO:

NAME:

#endif // _AFX_NO_AFXCMN_SUPPORT #define WM_MYTHREADMSG (WM_USER+1) //{{AFX_INSERT_LOCATION}} STEP 5: To map this message in MyThread.cpp file then add this message handler for this user defined message as follows BEGIN_MESSAGE_MAP(CMyThread, CWinThread) //{{AFX_MSG_MAP(CMyThread) // NOTE - the ClassWizard will add and remove mapping macros here. ON_THREAD_MESSAGE(WM_MYTHREADMSG,MyProc) //}}AFX_MSG_MAP END_MESSAGE_MAP() STEP 6: The message handler function for the message WM_MYTHREADMSG is MyProc. Write the function is in MyThread.cpp,

// CMyThread static y=50; static int cnt=0;


122

REG.NO:

NAME:

IMPLEMENT_DYNCREATE(CMyThread, CWinThread)

// CMyThread message handlers void CMyThread::MyProc(WPARAM,LPARAM) { CString str; CFrameWnd *pf; CView *pView; pf=(CFrameWnd *)AfxGetApp()->m_pMainWnd; pView=pf->GetActiveView(); CClientDC dc(pView); cnt++; str.Format("Thread : %d",cnt); dc.TextOut(50,y,str); y=y+20; } STEP 7: Open the MyThread.h file and change the CMyThread() constructor class from protected to public and add the declaration for the message handler function MyProc() in operations.

class CMyThread : public CWinThread


123

REG.NO:

NAME:

{ DECLARE_DYNCREATE(CMyThread) public: CMyThread(); // Attributes // Operations public: void MyProc(WPARAM,LPARAM); // Overrides STEP 8: Press Ctrl+w and add the message WM_LBUTTONDOWN for the baseclass CUserthreadView class.

STEP 9: Open the userthreadView.cpp file and edit the code for the message handler OnLButtonDown

// CUserthreadView message handlers void CUserthreadView::OnLButtonDown(UINT nFlags, CPoint point) { // TODO: Add your message handler code here and/or call default
124

REG.NO:

NAME:

CMyThread* ptr; ptr=new CMyThread(); ptr->CreateThread(); ptr->PostThreadMessage(WM_MYTHREADMSG,NULL,NULL); CView::OnLButtonDown(nFlags, point); } STEP 10 : Include the header file at the top of the userthreadView.cpp file, just above the #include userthreadDoc.h

#include "MyThread.h" #include "userthreadDoc.h" STEP 11: Build the Application and execute it.

OUTPUT :

RESULT : Thus the n number of threads were created using CreateThread function in MFCAppwizard.
125

REG.NO:

NAME:

Ex.No.16(b) Date :

WORKER THREAD

AIM : To create a worker thread using MFCAppwizard(exe). PROCEDURE : STEP 1: Start Visual C++, Select the MFCAppwizard(exe) and give the project name as workthread and select the single document option then simply click the next buttons by accepting the default values and finally click Finish button.

STEP 2: Goto ResourceView in workspace window and select the Menu folder. Click on the IDR_MAINFRAME then add the menu item Thread followed by the Start menu item, the properties as follows

126

REG.NO:

NAME:

STEP 3: Press Ctrl+W and click on the COMMAND message then add the message handler OnThreadStart for Start menu item.

STEP 4: Goto MainFrm.cpp file and edit the code for this message handler and finally Call the Worker thread using AfxBeginThread function in MainFrm.cpp as follows

127

REG.NO:

NAME:

// CMainFrame message handlers int m_cnt=0; UINT MyProc(LPVOID param) { CString msg; for(m_cnt=0;m_cnt<5;::InterlockedIncrement((long*)&m_cnt)) { msg.Format("Thread count %d",m_cnt); ::MessageBox((HWND)param,"Thread in execution...",msg,MB_OK); } return 0; } void CMainFrame::OnThreadStart() { // TODO: Add your command handler code here AfxBeginThread(MyProc,GetSafeHwnd(),THREAD_PRIORITY_NORMAL); } STEP 5: Build the Application and execute it.

OUTPUT:

RESULT : Thus the new thread has been created using Worker Thread in MFCAppwizard.

128