You are on page 1of 57

Dr.N.N.C.

MCA / IV

VP LAB-LM

MC9246-VISUAL PROGRAMMING LAB


LABORATORY MANUAL
FOR IV SEMESTER MCA
(FOR PRIVATE CIRCULATION ONLY)

ANNA UNIVERSITY ,CHENNAI

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


Dr. NAVALAR NEDUNCHEZHIYAN COLLEGE OF ENGINEERING
THOLUDUR 606303,CUDDALORE DISTRICT

Dr.N.N.C.E

MCA / IV

VP LAB-LM

GENERAL INSTRUCTIONS FOR LABORATORY CLASSES


DOS
o

Without Prior permission do not enter into the Laboratory.

While entering into the LAB students should wear their ID cards.

The Students should come with proper uniform.

Students should sign in the LOGIN REGISTER before entering into the laboratory.

Students should come with observation and record note book to the laboratory.

Students should maintain silence inside the laboratory.

After completing the laboratory exercise, make sure to shutdown the system properly.

DONTS
o Students bringing the bags inside the laboratory..
o Students wearing slippers/shoes insides the laboratory.
o Students using the computers in an improper way.
o Students scribbling on the desk and mishandling the chairs.
o Students using mobile phones inside the laboratory.
o Students making noise inside the laboratory.

Dr.N.N.C.E

MCA / IV

VP LAB-LM

HARDWARE REQUIREMENTS:
INTEL PENTIUM 915 GV
80GB HDD
512MB DDR

SOFTWARE REQUIREMENTS:
Visual Basic

UNIVERSITY PRACTICAL EXAMINATION

Allotment of marks
Internal assessment
=
20 marks
Practical assessment
=
80 marks
--------------Total
=
100 marks
---------------

INTERNAL ASSESSMENT (20 marks)


Staff should maintain the assessment Register and the Head of the Department should monitor it.
SPLIT UP OF INTERNAL MARKS

Observation
Record Note
Modal Exam
Attendance
Total

=
3 marks
=
7 marks
=
5 marks
=
5 marks
--------------------=
20 marks
---------------------

UNIVERSITY EXAMINATION
The exam will be conducted for 100 marks. Then the marks will be calculated to 80 marks.
SPLIT UP OF PRACTICAL EXAMINATION MARKS

Aim and Algorithm


Program
Output
Viva-voce

Total

=
=
=
=

30 marks
40 marks
20 marks
10 marks

-------------100 marks
--------------

Dr.N.N.C.E

MCA / IV

VP LAB-LM

MC9246 VISUAL PROGRAMMING LABORATORY


LIST OF EXPERIMENTS

VB
1. Form Design Keyboard & Mouse events
2. Programs on usage of data types - variant, Control arrays
3. Simple applications using file system controls
4. Database applications using data control.
VC++
1. SDK type programs for creating simple windows with different window styles
2. SDK type programs code for keyboard and mouse events, GDI objects.
3. Simple Dialog Based application eg. Calculator, interest computation, money
conversions, etc.
4. Creating SDI & MDI applications, Modal and Modeless dialog.
5. Programming for reading and writing into documents.
6. Coding Dynamic controls slider control, progress control, inheriting CtreeView and
CricheditView.
7. Creating static and dynamic splitter windows
8. Creating DLLs and using them.
9. Winsock and WinInet & Internet Explorer common controls.
10. Data access through ODBC Cdatabase, Crecordset.
11. Creating ActiveX control and using it.

Dr.N.N.C.E

MCA / IV

VP LAB-LM

CONTENTS

S.
No

Name of the Experiment

Visual Basic

Form Design Keyboard & Mouse events


Programs on usage of data types - variant, Control

2
3
4

arrays
Simple applications using file system controls
Database applications using data control
VC++

5
6
7

SDK type programs for creating simple windows


with different window styles
SDK type programs code for keyboard and mouse
events, GDI objects.
Simple Dialog Based application

10

Creating SDI & MDI applications, Modal and


Modeless dialog.
Programming for reading and writing into
documents.
Dynamic controls

11

static and dynamic splitter windows

12

DDL

8
9

Winsock and WinInet & Internet Explorer common

13

controls.

14

Data access through ODBC

15

Creating ActiveX control

Pg.No.

Dr.N.N.C.E

MCA / IV

VP LAB-LM

Exercise Number: 1
Title of the Exercise

Date of the Exercise

Form Design Keyboard & Mouse events

OBJECTIVE (AIM) OF THE EXPERIMENT

To Create a form and interact with the mouse and keyboard using VB.

FACILITIES REQUIRED AND PROCEDURE


a)

Facilities Required:
S.No.

Facilities required

Quantity

System

O/S

Windows XP

S/W name

Microsoft Visual Studio 6.0

b) Procedure:
Step

Details of the step

no.
1

Start programs Microsoft Visual Studio6.0Microsoft Visual Basic.

Visual basic can be opened.

Select FileNewstandard.exe , then give the project name and then


choose empty project button and finally give finishOK.

Design the form.

Type the coding.

Build and test the application

c) Program:
Private Sub cmd_Exit_Click()
Unload Me
End Sub
Private Sub cmd_Ok_Click()
MsgBox " Reg.NO: " & txt_RegNo.Text & " Name: " & _
txt_name.Text & " Address: " & txt_address.Text & _
" Branch: " & txt_Branch.Text
End Sub

Dr.N.N.C.E
MCA / IV
Private Sub Lbl_Message_DblClick()
MsgBox (" this is a label to show the events and messages")
End Sub

VP LAB-LM

Private Sub txt_Address_LostFocus()


Lbl_Message.Caption = "txt_Address_LostFocus event"
End Sub
Private Sub Txt_Name_Change()
Lbl_Message.Caption = "No. of letters in name :" & Len(txt_name.Text)
End Sub
Private Sub txt_RegNo_GotFocus()
Lbl_Message.Caption = "txt_RegNo_GotFocus event"
End Sub

d)

Output

e) Result:

`Thus the program has been executed successfully.

VIVA - QUESTIONS
1. What are the different types of text editing tools?
Edit control and Windows rich edit common control
The MFC library supports this versatility with the CEditView and CRichEditView
classes.
2.How one can create a new Toolbar? (A.U.May-2010) (A.U. May-2012)
To create toolbar, select toolbar from the Resource tab of the workspace pane and double
click on IDR_MAINFRAME. Now, the toolbar dialog window appears. Double click on the blank
tool and drag a control from the tools control and drop it in the toolbar drawing area. Now view
the ID of the tool from the properties dialog of the tool created.
7

Dr.N.N.C.E

MCA / IV

VP LAB-LM

Exercise Number: 2
Title of the Exercise

Date of the Exercise

Programs on usage of data types - variant, Control arrays

OBJECTIVE (AIM) OF THE EXPERIMENT

To create an application with the data types, variants, and array using VB.

FACILITIES REQUIRED AND PROCEDURE


a) Facilities Required:
S.No.

Facilities required

Quantity

System

O/S

Windows XP

S/W name

Microsoft Visual Studio 6.0

b) Procedure:
Step

Details of the step

no.
1

Start programs Microsoft Visual Studio6.0Microsoft Visual Basic.

Visual basic can be opened.

Select FileNewstandard.exe , then give the project name and then


choose empty project button and finally give finishOK.

Design the form.

Type the coding.

Build and test the application

c) Program:
Private Sub Form_Load( )
Me.WindowState=2
End Sub
Private Sub Option1_Click( )
If Option1.Value=True Then
Text3.Text=Val(Text1.Text]+Val(Text2.Text)
End Sub
Private Sub Option2_Click( )
If Option1.Value=True Then
Text3.Text=Val(Text1.Text]-Val(Text2.Text)
8

Dr.N.N.C.E

MCA / IV

VP LAB-LM

End Sub
Private Sub Option3_Click( )
If Option1.Value=True Then
Text3.Text=Val(Text1.Text]*Val(Text2.Text)
End Sub
Private Sub Option4_Click( )
If Option1.Value=True Then
Text3.Text=Val(Text1.Text]/Val(Text2.Text)
End Sub

d) Output

e) Result:
`
Thus the program has been executed successfully.

VIVA - QUESTIONS
1. How one can assign the tool tips in a toolbar?
i. To create a ToolTip, you simply add the tip text to the end of the menu
prompt, preceded by a newline (\n) character. The resource editor lets you
edit the prompt string while you are editing the toolbar images. Just doubleclick in the left panel.
2. Explain the status bar definitions.
ii. The status bar window neither accepts user input nor generates command
messages. The status bar supports two types of text panesmessage line
panes and status indicator panes.
iii. The static indicators array that AppWizard generates in the MainFrm.cpp
file defines the panes for the application's status bar. The
CStatusBar::SetIndicators member function, called in the application's
derived frame class, configures the status bar according to the contents of
the indicators array.
9

Dr.N.N.C.E

MCA / IV

VP LAB-LM

Exercise Number: 3
Title of the Exercise

Date of the Exercise

Simple applications using file system controls

OBJECTIVE (AIM) OF THE EXPERIMENT

To Create an application for file system controls using VB.

FACILITIES REQUIRED AND PROCEDURE


a) Facilities Required:
S.No.

Facilities required

Quantity

System

O/S

Windows XP

S/W name

Microsoft Visual Studio 6.0

b) Procedure:
Step

Details of the step

no.
1

Start programs Microsoft Visual Studio6.0Microsoft Visual Basic.

Visual basic can be opened.

Select FileNewstandard.exe , then give the project name and then choose empty
project button and finally give finishOK.

Design the form.

Type the coding.

Build and test the application

c) Program:
Private Sub Dir1_Change()
File1.Path = Dir1.Path
End Sub
Private Sub Drive1_Change()
Dir1.Path = Drive1.Drive
End Sub
Private Sub cmd_ListAllDrives_Click()
' Scan the contents of the DriveListBox control
List1.Clear
List1.AddItem "LIST OF DRIVES"
For i = 0 To Drive1.ListCount - 1
List1.AddItem Drive1.List(i)
10

Dr.N.N.C.E
Next
End Sub

MCA / IV

Private Sub cmd_ListAllFiles_Click()


' Scan the contents of the FileListBox control
List1.Clear
List1.AddItem "LIST OF FILES"
For i = 0 To File1.ListCount - 1
List1.AddItem File1.List(i)
Next
End Sub
Private Sub cmd_ListAllSubFolders_Click()
' Scan the contents of the DirListBox control
List1.Clear
List1.AddItem "LIST OF SUBFOLDERS"
For i = 0 To Dir1.ListCount - 1
List1.AddItem Dir1.List(i)
Next
End Sub
Private Sub cmd_ListAllParentFolders_Click()
List1.Clear
List1.AddItem "LIST OF PARENT FOLDERS"
pDepth = -1
While Dir1.List(pDepth) <> ""
List1.AddItem Dir1.List(pDepth)
pDepth = pDepth - 1
Wend
List1.AddItem "The current folder is nested " & _
-pDepth + 1 & " folders deep"
End Sub

d) Output

11

VP LAB-LM

Dr.N.N.C.E

MCA / IV

VP LAB-LM

e) Result:

Thus the program has been executed successfully.

VIVA - QUESTIONS
1. Explain the CFormView class.
iv. A CFormView object receives notification messages directly from its
controls, and it receives command messages from the application
framework. This application framework command-processing ability clearly
separates CFormView from CDialog, and it makes controlling the view from
the frame's main menu or toolbar easy.
v. The CFormView class is derived from CView (actually, from CScrollView)
and not from CDialog. You can't, therefore, assume that CDialog member
functions are supported. CFormView does not have virtual OnInitDialog,
OnOK, and OnCancel functions.
2.Define TRACE macro.
vi. TRACE statements are active whenever the constant _DEBUG is defined
(when you select the Debug target and when the afxTraceEnabled variable
is set to TRUE). TRACE statements work like C language printf statements,
but they're completely disabled in the release version of the program. Here's
a typical TRACE statement:

vii. int nCount = 9;


viii. CString strDesc("total");
ix. TRACE("Count = %d, Description = %s\n", nCount, strDesc);
3.What do you mean by serialization?
x. The idea is that objects can be persistent, which means they can be saved on
disk when a program exits and then can be restored when the program is
restarted. This process of saving and restoring objects is called serialization.
4.What are the classes used in MDI applications?
xi. Six classes are used in MDI. They are,
CView, CDocument, CDialog, CWinApp, CMainFrame, CChildFrame
12

Dr.N.N.C.E

MCA / IV

VP LAB-LM

Exercise Number: 4
Title of the Exercise

Date of the Exercise

Database applications using data control

OBJECTIVE (AIM) OF THE EXPERIMENT

To Create an database using data control and implement it in an application using


VB.

FACILITIES REQUIRED AND PROCEDURE


a) Facilities Required:
S.No.

Facilities required

Quantity

System

O/S

Windows XP

S/W name

Microsoft Visual Studio 6.0

b) Procedure:
Step

Details of the step

no.
1

Start programs Microsoft Visual Studio6.0Microsoft Visual Basic.

Visual basic can be opened.

Select FileNewstandard.exe , then give the project name and then


choose empty project button and finally give finishOK.

Design the form.

Type the coding.

Build and test the application

c) Program:
Dim db As Database
Dim rs As Recordset
Dim rs1 As Recordset
Dim sql As String
Private Sub Cmd_Delete_Click()
Set rs1 = db.OpenRecordset("select count(*) from student1 where rollno=" & _
Val(Txt_ROllNo.Text))
If Txt_ROllNo.Text = "" Then
MsgBox "enter a valid roll number"
Exit Sub
13

Dr.N.N.C.E
MCA / IV
End If
If rs1(0) = 0 Then
MsgBox ("there are no records with this roll number")
Exit Sub
End If
db.Execute ("delete from student1 where rollno=" & _
Val(Txt_ROllNo.Text))
MsgBox ("record deleted")
End Sub
Private Sub Cmd_Edit_Click()
Clear_Controls
Cmd_Edit.Enabled = False
End Sub
Private Sub cmd_Exit_Click()
Unload Me
End Sub
Private Sub Cmd_Save_Click()
If Cmd_Insert.Enabled = False Then
sql = " insert into student1 values(" & _
CInt(Txt_ROllNo.Text) & ",'" & _
Txt_Name.Text & "','" & _
Txt_Address.Text & "'," & _
CDbl(Txt_MobileNumber.Text) & ")"
MsgBox sql
db.Execute (sql)
MsgBox ("record inserted")
Cmd_Insert.Enabled = True
End If
If Cmd_Edit.Enabled = False Then
sql = "update student1 set name='" & Txt_Name.Text & " ',address='" & _
Txt_Address.Text & "',mobilenumber=" & _
CDbl(Txt_MobileNumber.Text) & " where (RollNO= " & _
CInt(Txt_ROllNo.Text) & ")"
MsgBox sql
db.Execute (sql)
MsgBox ("record updated")
Cmd_Edit.Enabled = True
End If
End Sub
Private Sub Form_Load()
Set db = OpenDatabase("D:\pavan\VbLabManual\Prg1\mca1.mdb", True)
Set rs = db.OpenRecordset("student1", dbOpenDynaset)
rs.MoveFirst
14

VP LAB-LM

Dr.N.N.C.E
'Show_Data

MCA / IV

End Sub
Private Sub Cmd_First_Click()
rs.MoveFirst
Show_Data
End Sub
Private Sub Cmd_Last_Click()
rs.MoveLast
Show_Data
End Sub
Private Sub Cmd_Next_Click()
rs.MoveNext
Show_Data
End Sub
Private Sub Cmd_Previous_Click()
rs.MovePrevious
Show_Data
End Sub
Private Sub Cmd_Insert_Click()
Clear_Controls
Cmd_Insert.Enabled = False
Txt_ROllNo.SetFocus
End Sub
Private Sub Show_Data()
If rs.EOF Then
rs.MoveLast
End If
If rs.BOF Then
rs.MoveFirst
End If
Txt_ROllNo.Text = rs(0)
Txt_Name.Text = rs(1)
Txt_Address.Text = rs(2)
Txt_MobileNumber.Text = rs(3)
End Sub
Private Sub Clear_Controls()
Txt_ROllNo.Text = ""
Txt_Name.Text = ""
Txt_Address.Text = ""
Txt_MobileNumber.Text = ""
End Sub

15

VP LAB-LM

Dr.N.N.C.E

MCA / IV

VP LAB-LM

d) Output

e) Result:
Thus the program has been executed successfully.
VIVA - QUESTIONS
1. What do you mean by SQL?
Structured Query Language (SQL), a standard database access language with its own
grammar. In the SQL world, a database is a collection of tables that consist of rows and columns.
Many DBMS products support SQL, and many programmers know SQL.
2. What Databases Can You Open with DAO? (A.U.APRIL 2007)
Opening an Access database (MDB file)An MDB file is a self-contained database that
includes query definitions, security information, indexes, relationships, and of course the actual
data tables. You simply specify the MDB file's pathname.
Opening an ODBC data source directlyThere's a significant limitation here. You can't
open an ODBC data source that uses the Jet engine as a driver; you can use only data sources that
have their own ODBC driver DLLs.
Attaching external tables to an Access databaseThis is actually the preferred way of
using DAO to access ODBC data. First you use Access to attach the ODBC tables to an MDB file,
and then you use DAO to open the MDB file as in the first option. You can also use Access to
attach ISAM files to an MDB file.
16

Dr.N.N.C.E

MCA / IV

VP LAB-LM

Exercise Number: 5
Title of the Exercise

Date of the Exercise

Windows Creation Program

OBJECTIVE (AIM) OF THE EXPERIMENT

To Create a simple window using vc++ programming

FACILITIES REQUIRED AND PROCEDURE


a) Facilities Required:
S.No.

Facilities required

Quantity

System

O/S

Windows XP

S/W name

Microsoft Visual Studio 6.0

b) Procedure:
Step

Details of the step

Start programs Microsoft Visual Studio6.0Microsoft Visual C++6.0.

Visual C++ Window will be opened.

Select FileNewWin32 Application, then give the project name and


then choose empty project button and finally give finishOK.

Again go to FileNewC++ Source FileFile NameOK.

Type the coding.

Build and test the application

c) Program:
#include <windows.h>
LRESULT CALLBACK WndProc(HWND,UINT,WPARAM,LPARAM);
int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,PSTR
szCmdLine,int iCmdShow)
{
static TCHAR szAppName[]=TEXT("HelloWin");
HWND hwnd;
MSG msg;
WNDCLASS win1;
17

Dr.N.N.C.E

MCA / IV

VP LAB-LM

win1.style=CS_HREDRAW|CS_VREDRAW;
win1.lpfnWndProc=WndProc;
win1.cbClsExtra=0;
win1.cbWndExtra=0;
win1.hInstance=hInstance;
win1.hIcon=LoadIcon(NULL,IDI_APPLICATION);
win1.hCursor=LoadCursor(NULL,IDC_WAIT);
win1.hbrBackground=(HBRUSH)GetStockObject(WHITE_BRUSH);
win1.lpszMenuName=NULL;
win1.lpszClassName=szAppName;
if(!RegisterClass(&win1))
{
MessageBox(0,"welcome",szAppName,MB_OK);
return FALSE;
}
hwnd=CreateWindow(szAppName,"vasanth",WS_OVERLAPPEDWINDOW,10,20,500,4
00,NULL,NULL,hInstance,NULL);
ShowWindow(hwnd,iCmdShow);
UpdateWindow(hwnd);
while(GetMessage(&msg,0,0,0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return (0);
}
LRESULT CALLBACK WndProc(HWND hwnd,UINT message,WPARAM
wParam,LPARAM lParam)
{
HDC hdc;
PAINTSTRUCT ps;
RECT rect;
switch(message)
{
18

Dr.N.N.C.E

MCA / IV

case WM_PAINT:
hdc=BeginPaint(hwnd,&ps);
GetClientRect(hwnd,&rect);
DrawText(hdc,TEXT("Hello"),1,&rect,DT_SINGLELINE|DT_CENTER|DT_VCENTER);
EndPaint(hwnd,&ps);
return(0);
case WM_DESTROY:
PostQuitMessage(0);
return(0);
}
return DefWindowProc(hwnd,message,wParam,lParam);

}
d) Output

e) Result:
Thus the program has been executed successfully.

VIVA - QUESTIONS
1.Define WINAPI?(A.U.APRIL 2007)
The WINAPI identifier is defined in WINDEF.H with the statement:
#define WINAPI __stdcall
19

VP LAB-LM

Dr.N.N.C.E

MCA / IV

VP LAB-LM

This statement specifies a calling convention that involves how machine code is
generated to place function call arguments on the stack. Most Windows function calls are
declared as WINAPI.
2.What is use of Message Box function?
The Message Box function is used to display short messages. The little window
that Message Box displays is actually considered to be a dialog box.
3. What are the function calls used in windows programming?
LoadIcon Loads an icon for use by a program.
LoadCursor Loads a mouse cursor for use by a program.
GetStockObject Obtains a graphic object, in this case a brush used for painting the
window's background.

RegisterClass Registers a window class for the program's

window. \
MessageBox Displays a message box.
CreateWindow Creates a window based on a window class.
4. What is a Handle? What is its advantage?
A handle is simply a number (usually 32 bits in size) that refers to an object. The handles in
Windows are similar to file handles used in conventional C or MS-DOS programming. A program
almost always obtains a handle by calling a Windows function. The program uses the handle in
ther Windows functions to refer to the object. The actual value of the handle is unimportant to your
program, but the Windows module that gives your program the handle knows how to use it to
reference the object.
5.

How will you display the window? (APRIL 2007)


i. After the CreateWindow call returns, the window has been created internally
in Windows. Then call the following 2 functions,
a.ShowWindow (hwnd, iCmdShow);
The first argument is the handle to the window just created by CreateWindow.
Win Main.
The second argument is the iCmdShow value passed as a parameter to
.
ii. The ShowWindow function puts the window on the display. If the second
argument to ShowWindow is SW_SHOWNORMAL, the client area of the
window is erased with the background brush specified in the window class.
The function call
b. UpdateWindow (hwnd);
i. It causes the client area to be painted.

20

Dr.N.N.C.E

MCA / IV

VP LAB-LM

Exercise Number: 6
Title of the Exercise

Date of the Exercise

Keyboard and Mouse Event

OBJECTIVE (AIM) OF THE EXPERIMENT


To write a program for Keyboard and mouse event using Win 32 Application.
FACILITIES REQUIRED AND PROCEDURE
a) Facilities Required:
S.No.

Facilities required

Quantity

System

O/S

Windows XP

S/W name

Microsoft Visual Studio 6.0

b) Procedure:
Step
no.
1
2

Details of the step


Create a project named key mouse from File->New and select Win32Application
Create a c++ file from File->New then select C++ Source File and give the File name
as key mouse

Define the WNDCLASS structure and Register it using RegisterClass( )

Create the window using Create Window function with specifying parameters

Extract the message from the message queue and dispatch it to the procedure using
Get Message & Dispatch Message respectively
The

window

message

WM_LBUTTONDOWN,

WM_LBUTTONUP,

WM_MOUSEMOVE is generated when the mouse is clicked, released, and moved


respectively and its status information are stored in flag variables
The line is drawn between (x1,y1) and (x2,y2) using MoveToEx() and LineToEx(),

here (x1,y1) is the current mouse co-ordinates after mouse move the current mouse
co-ordinates stored in (x2,y2) then the next step it is assigned to (x1,y1).

Build and Execute from Build->Build keymouse.exe then Build->Execute


keymouse.exe

21

Dr.N.N.C.E

MCA / IV

VP LAB-LM

c) Program:
#include<windows.h>
LRESULT CALLBACK WndProc(HWND,UINT,WPARAM,LPARAM);

int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,PSTR szCmdLine,int


iCmdShow)
{
static TCHAR szAppName[]=TEXT("HelloWin");
HWND hwnd;
MSG msg;
WNDCLASS wndclass;
wndclass.style =CS_HREDRAW | CS_VREDRAW;
wndclass.lpfnWndProc =WndProc;
wndclass.cbClsExtra =0;
wndclass.cbWndExtra =0;
wndclass.hInstance =hInstance;
wndclass.hIcon =LoadIcon(NULL,IDI_APPLICATION);
wndclass.hCursor =LoadCursor(NULL,IDC_ARROW);
wndclass.hbrBackground=(HBRUSH)GetStockObject(WHITE_BRUSH);
wndclass.lpszMenuName=NULL;
wndclass.lpszClassName=szAppName;
if(!RegisterClass(&wndclass))
{
MessageBox(NULL,TEXT("This prog requires windows
NT"),szAppName,MB_ICONERROR);
}
hwnd=CreateWindow(szAppName,TEXT("The Hello
Program"),WS_OVERLAPPEDWINDOW,CW_USEDEFAULT,CW_USEDEFAULT,CW_USE
DEFAULT,CW_USEDEFAULT,NULL,NULL,hInstance,NULL);

ShowWindow(hwnd,iCmdShow);
UpdateWindow(hwnd);
while(GetMessage(&msg,NULL,0,0))
{
22

Dr.N.N.C.E

MCA / IV

VP LAB-LM

TranslateMessage(&msg);
DispatchMessage(&msg);
}
return msg.wParam;
}
LRESULT CALLBACK WndProc(HWND hwnd,UINT message,WPARAM wParam,LPARAM
lParam)
{
HDC hdc;
static int x1,y1,x2,y2,flag=0;
switch(message)
{
case WM_LBUTTONDOWN:
if(flag==0)
{
x1=LOWORD(lParam);
y1=HIWORD(lParam);
flag=1;
}
return 0;
case WM_MOUSEMOVE:
if(flag==1)
{
x2=LOWORD(lParam);
y2=HIWORD(lParam);
hdc=GetDC(hwnd);
MoveToEx(hdc,x1,y1,0);
LineTo(hdc,x2,y2);
x1=x2;
y1=y2;
}
return 0;
case WM_LBUTTONUP:
flag=0;
23

Dr.N.N.C.E

MCA / IV
return 0;

case WM_KEYUP:
MessageBox(0,TEXT("Up Key is Pressed"),TEXT("Key
Information"),MB_ICONINFORMATION);
break;

case WM_KEYDOWN:
MessageBox(0,TEXT("Down Key is Pressed"),TEXT("Key
Information"),MB_ICONINFORMATION);
break;

case WM_DESTROY:
PostQuitMessage(0);
return 0;
}
return DefWindowProc(hwnd,message,wParam,lParam);
}

d) Output:

e) Result:
Thus the program has been executed successfully.

24

VP LAB-LM

Dr.N.N.C.E

MCA / IV

VP LAB-LM

VIVA - QUESTIONS
1. What are the arguments available in WinMain () function?
WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int
nShowCmd);
2. Give the syntax for creating the window?
ii. hwnd = CreateWindow (szAppName, // window class name
iii. TEXT ("The Hello Program"), // window caption
iv. WS_OVERLAPPEDWINDOW, // window style
v. CW_USEDEFAULT// initial x osition
vi. CW_USEDEFAULT// initial y position
vii. CW_USEDEFAULT// initial x size
viii. CW_USEDEFAULT// initial y size
ix. NULL// parent window handle
x. NULL// window menu handle
xi. hInstance// program instance handle
3. Give the attributes of window class. (A.U.APRIL 2007)
typedef struct
{
INT

style;

NDPROC

lpfnWndProc;

int

cbClsExtra;

int

cbWndExtra;

INSTANCE hInstance;
HICON
CURSOR

hIcon;
hCursor;

BRUSH

hbrBackground;

PCTSTR

lpszMenuName;

PCTSTR

lpszClassName;

WNDCLASS;
NDCLASS wndclass; }

25

Dr.N.N.C.E

MCA / IV

VP LAB-LM

Exercise Number: 7
Title of the Exercise

: Dialog based Application

Date of the Exercise

OBJECTIVE (AIM) OF THE EXPERIMENT


To perform the calculator operation using VC++ programming
FACILITIES REQUIRED AND PROCEDURE
a) Facilities Required:
S.No.

Facilities required

Quantity

System

O/S

Windows XP

S/W name

Microsoft Visual Studio 6.0

b) Procedure:
Step no.

Details of the step

Start programs Microsoft Visual Studio6.0Microsoft Visual C++6.0

File New MFC AppWizard (exe) project name ok.

Choose Dialog Based Applications finish.

Dialog box will be opened.

Design the dialog box like this.

Change each of the button name as 0,1,=,+

After adding button name the dialog box look like this.

Right click on the edit box and choose Class Wizard click on the Member
Variables
Tab and choose IDC_EDIT1Add Variable and member variable
name as m_t1

26

Dr.N.N.C.E

MCA / IV

VP LAB-LM

10

Click on the 0 button give the member function name and give 0K.

11

Add the Coding for each buttons like this.

12

In the CalcDlg header file under the construction comment line add the
declaration part.
i.e int index,val,data,data1;

13

double m,a,b;
char temp [10];
14

Build and test the application

c) Program:
//eDlg.h header file
int index,val,data,data1;
double m,a,b;
char temp[10];
//eDlg.cpp
void CEDlg::OnOne()
{
UpdateData(true);
if(m_t1=="0"|| m_t1==" ")
m_t1="1";
else
m_t1+="1";
UpdateData(false);
}
void CEDlg::OnZero()
{
UpdateData(true);
if(m_t1=="0"|| m_t1==" ")
m_t1="0";
else
m_t1+="0";
UpdateData(false);
}
void CEDlg::Ontwo()
{
UpdateData(true);
if(m_t1=="0"|| m_t1==" ")
m_t1="2";
else
m_t1+="2";
UpdateData(false);// TODO: Add your control notification handler code here
}
void CEDlg::Onthree()
27

Dr.N.N.C.E
MCA / IV
VP LAB-LM
{
UpdateData(true);
if(m_t1=="0"|| m_t1==" ")
m_t1="3";
else
m_t1+="3";
UpdateData(false);// TODO: Add your control notification handler code here
}
void CEDlg::Onfour()
{
UpdateData(true);
if(m_t1=="0"|| m_t1==" ")
m_t1="4";
else
m_t1+="4";
UpdateData(false);// TODO: Add your control notification handler code here
}
void CEDlg::Onfive()
{
UpdateData(true);
if(m_t1=="0"|| m_t1==" ")
m_t1="5";
else
m_t1+="5";
UpdateData(false);// TODO: Add your control notification handler code here
}
void CEDlg::Onsix()
{
UpdateData(true);
if(m_t1=="0"|| m_t1==" ")
m_t1="6";
else
m_t1+="6";
UpdateData(false);// TODO: Add your control notification handler code here
}
void CEDlg::Onseven()
{
UpdateData(true);
if(m_t1=="0"|| m_t1==" ")
m_t1="7";
else
m_t1+="7";
UpdateData(false);// TODO: Add your control notification handler code here
}
void CEDlg::Oneight()
{
28

Dr.N.N.C.E
MCA / IV
VP LAB-LM
UpdateData(true);
if(m_t1=="0"|| m_t1==" ")
m_t1="8";
else
m_t1+="8";
UpdateData(false);// TODO: Add your control notification handler code here
}
void CEDlg::Onnine()
{
UpdateData(true);
if(m_t1=="0"|| m_t1==" ")
m_t1="9";
else
m_t1+="9";
UpdateData(false);// TODO: Add your control notification handler code here
}
void CEDlg::Onsine()
{
UpdateData(true);
m=atof(m_t1);
m=(m*3.14)/180;
a=sin(m);
sprintf(temp,"%f",a);
m_t1=temp;
UpdateData(false);
}
void CEDlg::Onclear()
{
UpdateData(true);
m_t1="0";
UpdateData(false);
}
void CEDlg::Onequal()
{
UpdateData(true);
switch(index)
{
case 0:
{
UpdateData(true);
a=atof(m_t1);
b=a+m;
sprintf(temp,"%f",b);
m_t1=temp;
UpdateData(false);
break;
}
29

Dr.N.N.C.E
case 1:

MCA / IV

VP LAB-LM

{
UpdateData(true);
a=atof(m_t1);
b=-a;
sprintf(temp,"%f",b);
m_t1=temp;
UpdateData(false);
break;
}
case 2:
{
UpdateData(true);
a=atof(m_t1);
b=a*m;
sprintf(temp,"%f",b);
m_t1=temp;
UpdateData(false);
break;
}
case 3:
{
UpdateData(true);
a=atof(m_t1);
b=m/a;
sprintf(temp,"%f",b);
m_t1=temp;
UpdateData(false);
break;
}
}
UpdateData(false);
}
void CEDlg::Onclear()
{
UpdateData(true);
m_t1="0";
UpdateData(false);

// TODO: Add your control notification handler code here

}
void CEDlg::Onplus()
{
UpdateData(true);
m=atof(m_t1);
m_t1=" ";
index=0;
UpdateData(false);
}}

30

Dr.N.N.C.E
d)

MCA / IV

VP LAB-LM

Output:

e) Result:

Thus the program has been executed successfully.

VIVA QUESTION AND ANSWER


1. Why we need Visual C++?( A.U.May-2010)
The Visual C++ tools reduce coding drudgery
Graphical User Interface
Using MFC, which simplify and speed development of windows applications.
It includes sophisticated resource editors to design complex dialog boxes, menus,
toolbars, images and many other elements of modern windows applications.
2. What are the applications used in AppWizard? (A.U. May-2012)
a. Single Document Interface
b. Multiple Document Interface
c. Dialog Based
3. How one can add a new menu item in a dialog window?
To create a new menu bar by using resource editor, give the name as newmenu.Open
the dialog window, then select the dialog property window. Now select the menu property,
choose newmenu option.we can construct a CMenu object, use the CMenu::LoadMenu
function to load the menu from the resource, and call the CWnd::SetMenu function to attach
the new menu to the frame window.

31

Dr.N.N.C.E

MCA / IV

VP LAB-LM

Exercise Number: 8
Title of the Exercise

: MDI Application

Date of the Exercise

OBJECTIVE (AIM) OF THE EXPERIMENT


To create a MDI application to display a rectangle and apply pattern brush in it.
FACILITIES REQUIRED AND PROCEDURE
a) Facilities Required:
S.No.

Facilities required

Quantity

System

O/S

Windows XP

S/W name

Microsoft Visual Studio 6.0

b) Procedure:
Step no.
1
2

3
4

Details of the step


Create a project named MDI from File->New and select
MFCAppWizard(exe) and the next step select Multiple documents
and the next step uncheck the ActiveXControl support and finish it.
Use the Class Wizard to add WM_PAINT message to the View
class, to do select MDIView in both class name and Object IDs in
the Class Wizard then double click WM_PAINT message in the
Messages field
Edit the code for OnPaint message handler function
Build and execute the program, click File->New, a new document
is opened.

c) Program:
void CMDIView::OnPaint( )
{
CPaintDC dc(this); CBrush br;
br.CreateSolidBrush(RGB(255,0,0)); dc.SelectObject(br);
dc.Rectangle(20,30,80,95);
}

32

Dr.N.N.C.E

MCA / IV

VP LAB-LM

d) Output:

e) Result:
Thus the program has been executed successfully.

VIVA QUESTION AND ANSWER


1. Differentiate SDI and MDI.
The MFC library supports two distinct application types: Single Document Interface
(SDI) and Multiple Document Interface (MDI). An SDI application has, from the user's point
of view, only one window. If the application depends on disk-file "documents," only one
document can be loaded at a time. The original Windows Notepad is an example of an SDI
application. An MDI application has multiple child windows, each of which corresponds to an
individual document. Microsoft Word is a good example of an MDI application.
What is an MFC? (A.U.APRIL 2007) (A.U. May-2012)
MFC is a Microsoft Foundation Class.
MFC is an object-oriented interface to windows.
MFC encapsulates key windows data structures.
Goal of MFC, facilitating and simplifying the process of programming for Microsoft
windows.
MFC library is a collection of C++ classes, it is provided as a DLL.
What is the purpose of OnUpdate() function?
This virtual function is called by the application framework in response to your
application's call to the CDocument::UpdateAllViews function. Your derived view class's
OnUpdate function accesses the document, gets the document's data, and then updates the view's
data members or controls to reflect the changes.
33

Dr.N.N.C.E

MCA / IV

VP LAB-LM

Exercise Number: 9
Title of the Exercise

: Reading and Writing a Document

Date of the Exercise

OBJECTIVE (AIM) OF THE EXPERIMENT


To create a MFC application for reading and writing a document.
FACILITIES REQUIRED AND PROCEDURE
a) Facilities Required:
S.No.

Facilities required

Quantity

System

O/S

Windows XP

S/W name

Microsoft Visual Studio 6.0

b) Procedure:
Step

Details of the step

no.
1

Create project named Menu and accept all the default settings but two: select Single
Document and deselect Print Preview.

Click on the Resource view tab in the Workspace window. Edit the IDR_MAINFRAME
menu resources to add a separator and Clear Document item to the edit menu, as shown
here

Now add a Transfer menu, and then define the underlying items

Open IDR_MAINFRAME in the accelerator folder, And then use the insert key to add
the following items(turn off the Ctrl, Alt, Shift modifiers)
Accelerator ID

Key

ID_TRANSFER_GETDATA

VK_F2

ID_TRANSFER_STOREDA

VK_F3

TA
5

Use the class wizard to add the following message handler to the CMenuView class (in
34

Dr.N.N.C.E

MCA / IV

VP LAB-LM

the class wizard select CMenuView class)


Object ID

Message

Member Function

ID_TRANSFER_GETDAT

COMMAND

OnTransferGetData

COMMAND

OnTransferStoreData

ID_TRANSFER_STORED

UPDATE_COMMAND

OnUpdateTransferStore

ATA

_UI

Data

ID_TRANSFER_STORED
ATA
6

Use the class wizard to add the following message handler to the CMenuDoc class (in
the class wizard select CMenuDoc class)
Object ID

Message

Member Function

ID_EDIT_CLEARDOCUM

COMMAND

OnEditClearDocument

ENT

UPDATE_COMMAND

OnUpdateEditClearDocu

ID_EDIT_CLEARDOCUM

_UI

ment

ENT
7

In the class view window, right click on CMenuDoc class and select Add Member
Variable, now type CString as Varaible Type, m_strText as Variable Name and access
as public.

Edit the OnNewDocument, command handler function(added by us) in MenuDoc.cpp


(in the File View tab)

In the class view window, right click on CMenuView class and select Add Member
Variable, now type CRichEditCtrl as Varaible Type, m_rich as Variable Name and
access as public.

10

Open the Class Wizard (Ctrl+W), select CMenuView in class name field, select
CMenuView and double click WM_CREATE and WM_SIZE then accept the default
function handler name. Edit the code for the two handler functions and also edit
command handler function which is created by us.

11

Build and Execute the application.

c) Program:
// CMenuDoc.cpp
BOOL CMenuDoc::OnNewDocument()
{

if (!CDocument::OnNewDocument())
35

Dr.N.N.C.E

MCA / IV

VP LAB-LM

return FALSE;
m_strText="Hello(from CMenuDoc::OnNewDocument()";
// (SDI documents will reuse this document)
return TRUE;

}
void CMenuDoc::OnEditCleardocument()
{
m_strText.Empty(); }
void CMenuDoc::OnUpdateEditCleardocument(CCmdUI* pCmdUI)
{

pCmdUI->Enable(!m_strText.IsEmpty());

// CMenuView.cpp
int CMenuView::OnCreate(LPCREATESTRUCT lpCreateStruct)
{

CRect rect(0,0,0,0);
if (CView::OnCreate(lpCreateStruct) == -1)
return -1;
m_rich.Create(ES_AUTOVSCROLL|ES_MULTILINE|ES_WANTRETURN|WS_CHILD|

WS_VISIBLE|WS_VSCROLL,rect,this,1);
return 0;

void CMenuView::OnSize(UINT nType, int cx, int cy)


{

CRect rect;
GetClientRect(rect);

m_rich.SetWindowPos (&wndTop,0,0,rect.right-rect.left ,rect.bottom -rect.top


,SWP_SHOWWINDOW);
CView::OnSize(nType, cx, cy);

void CMenuView::OnTransferGetdata()
{

CMenuDoc* pDoc=GetDocument();
m_rich.SetWindowText (pDoc->m_strText);
m_rich.SetModify(FALSE);

void CMenuView::OnTransferStoredata()
{

CMenuDoc* pDoc=GetDocument();
m_rich.GetWindowText (pDoc->m_strText);
m_rich.SetModify(FALSE);

void CMenuView::OnUpdateTransferStoredata(CCmdUI* pCmdUI)


{

pCmdUI->Enable(m_rich.GetModify());

36

Dr.N.N.C.E

MCA / IV

d) Output:

e) Result:
Thus the program has been executed successfully.

37

VP LAB-LM

Dr.N.N.C.E

MCA / IV

VP LAB-LM

VIVA QUESTION AND ANSWER


1. Give the resources for SDI.
Resource
Accelerator

Dialog

Description
Definitions for keys that simulate menu and toolbar
selections.
Layout and contents of dialog boxes.
Icons (16-by-16-pixel and 32-by-32-pixel versions), such as

Icon

the application icon you see in Microsoft Windows Explorer


and in the applications About dialog box.

Menu

The application's top-level menu and associated pop-up


menus.

String table

Strings that are not part of the C++ source code.

Toolbar

The row of buttons immediately below the menu.

Version

Program description, version number, language, and so on.

2. Explain MainFrame Window.


The mainframe window has the title bar and the menu bar. Various child windows,
including the toolbar window, the view window, and the status bar window, occupy the
mainframe window's client area.
3. How one can create a new menu items?
To create a menu, select menu from the Resource tab of the workspace pane and double
click on IDR_MAINFRAME. Now the menu bar dialog window appears. Double click on the
last menu space and enter main menu name as the caption in the properties dialog box. In the
same manner add submenus.
4. What is the use of keyboard accelerator?
This shortcut system is the standard Windows method of using the keyboard to choose
commands from menus. If you look at an application's menu resource script (or the menu
editor's properties dialog), you will see an ampersand (&) preceding the character that is
underlined in each of the application's menu items.
38

Dr.N.N.C.E

MCA / IV

VP LAB-LM

Exercise Number: 10
Title of the Exercise

: DYNAMIC CONTROL

Date of the Exercise

OBJECTIVE (AIM) OF THE EXPERIMENT


To create a control using ATL wizard and use it in another application.
FACILITIES REQUIRED AND PROCEDURE
a) Facilities Required:
S.No.

Facilities required

Quantity

System

O/S

Windows XP

S/W name

Microsoft Visual Studio 6.0

b) Procedure:
Step no.
1

Details of the step


Create a new project named MY_ATL from File->New and select
ATLCOMAppWizard then the next step select Dynamic Link
Library(DLL) and click finish.

In the class view, right click on MY_ATL class then select New ATL
Object, a window will appear. Select simple object and type TEST_ATL
in the short name field then click on Attributes tab then select aggregation
is no.

In the class view, expand the CTEST_ATL then right click on


ITEST_ATL then choose Add Method, a dialog will appear no add the
following methods
Method Name

Parameters

add

[in] long a,[in] long b,[out long *c

sub

[in] long a,[in] long b,[out long *c

Edit the above methods and add code into it.

Now build the project (Dont execute it)

/*COM PROJECT USING VB*/


1

Create a VB project named COM using Microsoft visual Basic 6.0. Select
Standard Exe project
39

Dr.N.N.C.E
2

MCA / IV

VP LAB-LM

Design the form window


as shown below

Create a Type Library for ATL COM Object from Project->References


then click browse, now select MY_ATL.dll which is present in the Debug
folder of MY_ATL project folder (dll file is generated only when we
build the project) and then click ok.

Now double click each button (click form icon), functions to be added for
each command button. Add codes to the respective as shown in the
coding.

Run the project from Run->Start

c) Program:
//TEST_ATL.cpp
CTEST_ATL::sub(long a, long b, long *c)
{

*c=a-b;
return S_OK;

/*COM PROJECT USING VB*/


//COM.vbp
//general
Dim c As Long
Dim a As Long
Dim b As Long
Private Sub Command1_Click()
Dim obj As MY_ATLLib.TEST_ATL
Set obj = New TEST_ATL
a = Text1.Text
b = Text2.Text STDMETHODIMP CTEST_ATL::add(long a, long b, long *c)
{

*c=a+b;
40

Dr.N.N.C.E

MCA / IV

return S_OK;
}
STDMETHODIMP
obj.Add a, b, c
MsgBox " a=" & a & " b=" & b & " a+b=" & c
End Sub
Private Sub Command2_Click()
Dim obj As MY_ATLLib.TEST_ATL
Set obj = New TEST_ATL
a = Text1.Text
b = Text2.Text
obj.sub a, b, c
MsgBox " a=" & a & " b=" & b & " a-b=" & c
End Sub
Private Sub Command3_Click()
End
End Sub

d) Output:

e) Result:
Thus the program has been executed successfully.

41

VP LAB-LM

Dr.N.N.C.E

MCA / IV

VP LAB-LM

VIVA QUESTION AND ANSWER


1. What do you mean by COM?
The Component Object Model (COM) is the foundation of much of the new Microsoft
ActiveX technology. COM is an integral part of Programming Visual C++. COM is an
"industry-standard" software architecture supported by Microsoft, Digital Equipment
Corporation, and many other companies. It's by no means the only standard. Indeed, it
competes directly against other standards, such as CORBA from the Open Software
Foundation (OSF).
2. What are the features of COM?
COM provides a unified, expandable, object-oriented communications protocol for
Windows that already supports the following features:
A standard, language-independent way for a Win32 client EXE to load and call a
Win32 DLL. A general-purpose way for one EXE to control another EXE on the same
computer (the DDE replacement). A replacement for the VBX control, called an ActiveX
control. A powerful new way for application programs to interact with the operating system.
Expansion to accommodate new protocols such as Microsoft's OLE DB database
interface. The distributed COM (DCOM) that allows one EXE to communicate with another
EXE residing on a

different computer, even if the computers use different microprocessor-

chip families.
3. What is a COM Interface?
COM objects have methods. Methods are grouped into interfaces and are called through
interface pointers. Interfaces exist to semantically bind together groups of related
methods.Prefacing interface names with a capital I for Interface is an almost universal COM
programming convention.
Microsoft has predefined more than 100 interfaces that any COM object can support.
These interfaces are called standard interfaces. User-defined interfaces such as IMath and
ISpelling are custom interfaces. COM objects can use standard interfaces, custom interfaces, or
a combination of the two. Every COM object implements an interface named IUnknown.
IUnknown contains just three methods:
QueryInterface - Returns a pointer to another interface, AddRef - Increments the object's
reference count, Release - Decrements the object's reference count

42

Dr.N.N.C.E

MCA / IV

VP LAB-LM

Exercise Number: 12
Title of the Exercise : CREATING DLL-REGULAR USING SHARED MFC DLL
Date of the Exercise :
OBJECTIVE (AIM) OF THE EXPERIMENT
To create a DLL file and use the function of DLL in another EXE application.
FACILITIES REQUIRED AND PROCEDURE
a) Facilities Required:
S.No.

Facilities required

Quantity

System

O/S

Windows XP

S/W name

Microsoft Visual Studio 6.0

b) Procedure:
Step no.
1

Details of the step


Create a project MyDll from File->New, select the MFCAppWizard(dll)
and the next step select Regular DLL using shared MFC DLL

In the class view tab on the workspace right click on MyDll classes and
choose New Class, a dialog will appear, now choose the class type as
Generic class and type the class name as CMyClass and press OK.

In the class view tab right click on CMyClass and select Add Member
Function
Function type

Function Declaration

CString

SayHello(CString
strName)

In the File view tab on the workspace, open the Header file folder and
double click on the MyClass.h and add __declspec(dllexport) infront
of all functions that are used for external application.

In the File view tab on the workspace, open the MyClass.cpp from source
file folder and type the code.

Compile & Build the project


CREATING A NEW APPLICATION THAT USE THE DLL

Create a project named TestDll from File->New and select the


MFCAppwizard(exe) and the next step select Dialog based application
43

Dr.N.N.C.E

MCA / IV

VP LAB-LM

and accept the default values for the next step and finish it.
2

A dialog will appeared, now design the dialog window using controls just
look like as follows

Open class wizard from the view menu, click member variable tab and
choose IDC_EDIT1 and click add member variable and type as follows

Variable name

Category

CString

m_edit

value

CString

Double click the OK button on the dialog window, then the OnOk
function will be generated

In the file view tab on the work space window, open the TestDllDlg.h
to include MyClass.h and to declare object of that class and add the
codes to it

#include ..\MyDll\MyClass.h

Select the Project->Settings->Link and in the Object/library modules


enter a path to the DLL library file as follows
..\MyDll\Debug\MyDll.lib

Now copy the MyDll.dll file from MyDll\Debug folder and paste it into
the TestDll\Debug folder

Build and execute the project.

c) Program:
//MyClass.h
class CMyClass
{public:
44

Dr.N.N.C.E

MCA / IV

__declspec(dllexport)CString SayHello(CString strName);


__declspec(dllexport)CMyClass();
__declspec(dllexport)virtual ~CMyClass();
};
//MyClass.cpp
CString CMyClass::SayHello(CString strName)
{

return "HAI "+strName;

}
TESTDLL
//TestDllDlg.h
#include "..\MyDll\MyClass.h"
class CTestDllDlg : public CDialog
{public:
CMyClass objMyClass;
CTestDllDlg(CWnd* pParent = NULL);
};
//TestDllDlg.cpp
void CTestDllDlg::OnOK()
{

UpdateData(true);
CString str=objMyClass.SayHello(m_strText);
AfxMessageBox(str);
CDialog::OnOK();

}
d) Output:

e) Result:
Thus the program has been executed successfully.
45

VP LAB-LM

Dr.N.N.C.E

MCA / IV

VP LAB-LM

VIVA QUESTION AND ANSWER


1. What is a DLL?
A DLL is a file on disk (usually with a DLL extension) consisting of global data,
compiled functions, and resources, which become part of your process. It is compiled to load at
a preferred base address, and if there's no conflict with other DLLs, the file gets mapped to the
same virtual address in your process.
The DLL has various exported functions, and the client program (the program that
loaded the DLL in the first place) imports those functions. Windows matches up the imports
and exports when it loads the DLL.
2. How the Client Program Finds a DLL.
If we link explicitly with LoadLibrary, you can specify the DLL's full pathname. If we
don't specify the pathname, or if you link implicitly, Windows follows this search sequence to
locate your DLL:
The directory containing the EXE file
The process's current directory
The Windows system directory
The Windows directory
The directories listed in the path environment variable
Here's a trap you can easily fall into. We build a DLL as one project, copy the DLL file
to the system directory, and then run the DLL from a client program. Next we rebuild the DLL
with some changes, but we forget to copy the DLL file to the system directory. The next time
we run the client program, it loads the old version of the DLL.
3. What are the different types of DLL?
AppWizard lets you build two kinds of DLLs with MFC library support:
a. extension DLLs and
b. regular DLLs.
4. Explain the extension DLL?
An extension DLL dynamically links to the code in the DLL version of the MFC library. An
extension DLL supports a C++ interface. When we build an MFC regular DLL, you can choose
to statically link or dynamically link to the MFC library. If we choose static linking, our DLL
will include a copy of all the MFC library code it needs and will thus be self-contained.

46

Dr.N.N.C.E

MCA / IV

VP LAB-LM

Exercise Number: 14
Title of the Exercise : DATA ACCESS THROUGH ODBC
Date of the Exercise :
OBJECTIVE (AIM) OF THE EXPERIMENT
To create a MFC Application for Database to store, retrieve, update student
information like name, roll no, dept, mark1, mark2, and mark3 using ODBC.
FACILITIES REQUIRED AND PROCEDURE
a) Facilities Required:
S.No.

Facilities required

Quantity

System

O/S

Windows XP

S/W name

Microsoft Visual Studio 6.0

b) Procedure:
Step no.

Details of the step


CREATING DATABASE

Create a database for the project in MSAccess from File->New and crea
blank database and save it then do the following
i. On the dialog appears in the window double click the
create table in design view
ii. Now type the fields like as follows and save the table
Name

Text

RollNo

Number

Dept

Text

Mark1

Number

Mark2

Number

Mark3

Number

The table is shown, now specify the input or data for the fields
ACCESSING THE DATA
1

Create

project

name

ODBC

using

File->New

and

select

MFCAppWizard(exe) and the second step select Single Document and the
3rd step Database view without File support and click the data source on
47

Dr.N.N.C.E

MCA / IV

VP LAB-LM

the same dialog box and then


Select in ODBC database name that we created and click OK and then
table name will be displayed on the window and select it click ok
2

Now accept the next default steps and the last step the AppWizard will
creates five classes for the project and click finish

Now design the dialog window using controls as follows

On the client area design a mark list for the student using the controls and
set the IDs

control (Edit control)

IDs

Name

IDC_NAME

RollNo

IDC_ROLLNO

Dept

IDC_DEPT

Mark1

IDC_MARK1

Mark2

IDC_MARK2

Mark3

IDC_MARK3

Add member variable for the classes from view->class Wizard and select
the member variable tab on the dialog and do the following
i. Select the control IDs and click Add variable then a dialog appears
ii. In the new dialog, select the Member variable Name and the
variable type using the combo box.
Similarly do the above step for other control IDs.

The Member variables and its types are follows after finishing the
previous step.

48

Dr.N.N.C.E

MCA / IV
Control IDs

Type

IDC_DEPT

CString m_Dept

IDC_MARK1

int

m_Mark1

IDC_MARK2

int

m_Mark2

IDC_MARK3

int

m_mark3

IDC_NAME

CString m_Name

IDC_ROLLNO int
7

VP LAB-LM
Member

m_RollNo

Set the IDs for the buttons using its properties(right click)
Control IDs

Caption

ID_CLEAR

Clear

ID_ADD

Add

ID_DELETE

Delete

ID_UPDATE

Update

Now double click the buttons then corresponding handler are generated
and then add the codes to the corresponding handler
CONNECTING DATABASE TO OUR PROJECT

To make a connection of vc++ to MsAccess by following the steps.


i) From settings-> controlpanel-> Administrative tools->ODBC then a
dialog will appears.
ii) Click the add button on the dialog box then a dialog box appears, in
that select access drive to Microsoft access (*.mdb) and click ok.
iii) Then type a data source named and click select button and select the
database name mdb file and click ok and next boxes also click ok.

Now the connection to access data from database was established.

Build and execute the program.

In the output client window, using the next and previous record button.
We can see the record and also using the button we can insert, delete and
update the records.

c) Program:
// CODBCView.CPP
void CODBCView::OnClear()
{

m_pSet->SetFieldNull(NULL);
UpdateData(FALSE);
49

Dr.N.N.C.E

MCA / IV

}
void CODBCView::OnAdd()
{

m_pSet->AddNew();
UpdateData(TRUE);
if(m_pSet->CanUpdate())
{

m_pSet->Update();

if(m_pSet->IsEOF())
{

m_pSet->MoveLast();

m_pSet->Requery();
UpdateData(FALSE);

void CODBCView::OnDelete()
{

CRecordsetStatus stat;
try

m_pSet->Delete();

catch(CDBException* e)
{

AfxMessageBox(e->m_strError);
e->Delete();
m_pSet->MoveFirst();
UpdateData(FALSE);
return;

m_pSet->GetStatus(stat);
if(stat.m_lCurrentRecord==0)
{

m_pSet->MoveFirst();

m_pSet->MoveNext();

else
{

UpdateData(FALSE);
}
void CODBCView::OnUpdate()
{

m_pSet->Edit();
UpdateData(TRUE);
if(m_pSet->CanUpdate())
{

m_pSet->Update();

50

VP LAB-LM

Dr.N.N.C.E

MCA / IV

VP LAB-LM

d) Output:

e) Result:
Thus the program has been executed successfully.

VIVA QUESTION AND ANSWER


1. Define ODBC?
The Microsoft Open Database Connectivity (ODBC) standard defines the rules of
SQL grammar and also the C-language programming interface to any SQL database. It's
now possible for a single compiled C or C++ program to access any DBMS that has an
ODBC driver.
2. Explain ODBC architecture.
ODBC's unique DLL-based architecture makes the system fully modular. A small
top-level DLL, ODBC32.DLL, defines the API. ODBC32.DLL loads database-specific
DLLs, known as drivers, during program execution.
3. What are the Recordset member functions?
Open
- Opens the recordset
AddNew
- Prepares to add a new record to the table
Update
- Completes an AddNew or Edit operation by saving the new or
edited
1. data in the data source
Delete
- Deletes the current record from the recordset
4. What are the advantages of DBMS?
Use of standard file formats, Indexed file access, Data integrity safeguards, Multiuser access
control.
51

Dr.N.N.C.E

MCA / IV

VP LAB-LM

Exercise Number: 15
Title of the Exercise : CREATING ACTIVEX CONTROL AND USING IT
Date of the Exercise :
OBJECTIVE (AIM) OF THE EXPERIMENT
To create MFC Application for Active X Control Support.
FACILITIES REQUIRED AND PROCEDURE
a) Facilities Required:
S.No.

Facilities required

Quantity

System

O/S

Windows XP

S/W name

Microsoft Visual Studio 6.0

b) Procedure:
Step no.
1

Details of the step


Create a project named ActiveXCtrl from File->New and select
MFCAppWizard (exe) and the next step select Single Document after that
accept the default values and finish it.

From the project menu select add to project->components and controls


open Registered ActiveX controls and select calendar controls 8.0, now
click the insert button.

The classwizard generates two classes for the project. The classes are
CCalendar, COlefont and click ok.

In the resource view tab on the workspace, right click on dialog and select
insert, a new dialog box appears.

In the dialog box, right click it and select the properties, change the ID as
IDD_ACTIVEXDIALOG and caption as ActiveXDialog.

Drag the calendar control from the control palette and place it into the
dialog box and design the dialog box as shown below.

52

Dr.N.N.C.E

MCA / IV

VP LAB-LM

By using the properties, change the ID and caption as follow


Control

ID

Caption

Calendar control

IDC-

--

Selectdatebutton

CALENDAR1

select date

Editcontrol

IDC-

--

Editcontrol

SELECTDATE

--

Editcontrol

IDC-DAY

--

Nextweek button

IDC-MONTH

nextweek

IDC-YEAR
IDC-NEXTWEEK
8

From the view classwizard, select create a new class and type the name
as CActiveXDialog and click ok.

In the classwizard from view menu, select the message maps and add the
message handler as follows, (double click the messages)
Object IDs

Messages

CActiveXDialog

WM_INITDIALOG

IDC_SELECTDATE BN_CLICKED

10

IDC_NEXTWEEK

BN_CLICKED

IDC_CALENDAR1

NewMonth

ID_OK

BN_CLICKED

Click on the classwizard from view menu and select member variable tab
and then add the member variable as follows. To add variable just select
the IDs and click add variable button.
IDs

Member
53

Category

Variable

Dr.N.N.C.E

MCA / IV

VP LAB-LM

variable name

11

Type

IDC_CALENDER m_calender

control

CCalendar

IDC_DAY

m_sDay

value

short

IDC_MONTH

m_sMonth

value

short

IDC_YEAR

m_sYear

value

short

In the class view tab, on the workspace right click on CActiveXDialog


and choose add member variable as follows.

12

Variable Type

Variable Name

unsigned long

m-BackColor

COleVariant

m-varValue

Open the ActiveXDialog.cpp file from the file view tab and open source
files and add the codes to it.

13

From the view ->ClassWizard, choose CActiveXCtrlView in class name


field and select CActiveXCtrlView in Object IDs and double click
WM_UTTONDOWN in the messages list box and click ok.

14

Open the AxtiveXCtrlView.cpp and add codes to OnLButtonDowm()


handler as follows and add

#include ActiveXDialog.h at the top and

add the code to it.


15

Edit the OnDraw function and add code to it.

16

Build and execute the project.

c) Program:
// CActiveXCtrlView.cpp
void CActiveXCtrlView::OnDraw(CDC* pDC)
{

CActiveXCtrlDoc* pDoc = GetDocument();


ASSERT_VALID(pDoc);
pDC->TextOut(10,10,"press");
// TODO: add draw code for native data here

}
void CActiveXCtrlView::OnLButtonDown(UINT nFlags, CPoint point)
{

CActiveXDialog dlg;
dlg.m_BackColor=RGB(255,251,240);
COleDateTime today=COleDateTime::GetCurrentTime();
54

Dr.N.N.C.E

MCA / IV

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"));

}
CView::OnLButtonDown(nFlags, point);
}
// CActiveXDialog.cpp
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=0x000000F;

}
BOOL CActiveXDialog::OnInitDialog()
{

CDialog::OnInitDialog();
m_calendar.SetValue(m_VarValue);
return TRUE; // return TRUE unless you set the focus to a control

}
void CActiveXDialog::OnNextweek()
{

m_calendar.NextWeek();

}
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);
55

VP LAB-LM

Dr.N.N.C.E

MCA / IV

VP LAB-LM

}
void CActiveXDialog::OnOK()
{

CDialog::OnOK();
m_VarValue=m_calendar.GetValue();

}
void CActiveXDialog::OnNewMonthCalendar1()
{
AfxMessageBox("Event for new month from ActiveXDialog::OnNewMonthCalandar1");
}
d) Output:

e) Result:

Thus the program has been executed successfully.

VIVA QUESTION AND ANSWER


1. What is an ActiveX control?
An ActiveX control is a software module that plugs into your C++ program the same
way a Windows control does. You can consider an ActiveX control to be a child window, just
as an ordinary control is. The most prominent ActiveX Controls features are properties and
56

Dr.N.N.C.E

MCA / IV

VP LAB-LM

methods. ActiveX Controls (formerly known as OLE controls or OCXs) are the industrialstrength replacement for VBXs based on Microsoft COM technology. Application developers
in both VB and Visual C++ 6.0 can use ActiveX controls.
2. Give the properties, methods and events in a calendar control.
The MSCal.ocx control is a popular Microsoft ActiveX Calendar control that's probably
already installed and registered on your computer. The Calendar control comes with a help file
that lists the control's properties, methods, and events.

Properties

Methods

Events

BackColor

AboutBox

AfterUpdate

Day

NextDay

BeforeUpdate

DayFont

NextMonth

Click

DayFontColor

NextWeek

DblClick

DayLength

NextYear

KeyDown

FirstDay

PreviousDay

KeyPress

Month

PreviousMonth

KeyUp

MonthLength

PreviousWeek

NewMonth

ShowDays

PreviousYear

NewYear

ShowTitle

Refresh

TitleFont

Today

3. How one can create an ActiveX control at runtime.


Insert the component into your project. ClassWizard will create the files for a wrapper
class.
Add an embedded ActiveX control wrapper class data member to your dialog class or
other C++ window class. In embedded C++ object is then constructed and destroyed
along with the window object.

57

You might also like