0% found this document useful (0 votes)
96 views41 pages

Annamalai University

The document provides solutions to programming exercises using Visual Basic and Visual Programming. The exercises include: 1) Accepting a number from the user and displaying a series. 2) Checking if a string is a palindrome. 3) Resizing a form and updating the height and width labels accordingly. 4) Changing a label text using input from a textbox in a user control. 5) Using listboxes to add and remove items. 6) Searching for a file with a given name pattern in the system. 7) Designing a form using a flexigrid control and populating it from a database using inputs from a combobox. The solutions provide the necessary

Uploaded by

Green Zone
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
96 views41 pages

Annamalai University

The document provides solutions to programming exercises using Visual Basic and Visual Programming. The exercises include: 1) Accepting a number from the user and displaying a series. 2) Checking if a string is a palindrome. 3) Resizing a form and updating the height and width labels accordingly. 4) Changing a label text using input from a textbox in a user control. 5) Using listboxes to add and remove items. 6) Searching for a file with a given name pattern in the system. 7) Designing a form using a flexigrid control and populating it from a database using inputs from a combobox. The solutions provide the necessary

Uploaded by

Green Zone
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

IT0216

ANNAMALAI UNIVERSITY
DIRECTORATE OF DISTANCE EDUCATION

MSc INFORMATION TECHNOLOGY


FIRST SEMESTER

PROGRAMMING LAB – II
VISUAL PROGRAMMING
Annamalai University

Copyright Reserved
(For Private Circulation Only)
Visual Programming

Visual Basic

Lab Manual
1. Accept a number from user and display the series till the given number.
(for ex: if 3 is input display series as follows:
1
2 2
3 3 3)

Solution

Form Layout

Option Explicit
Private Sub cmdDisplay_Click()
If txtDisp_Number.Text <= 0 Then
Exit Sub
End If
Dim I As Integer, K As Integer, strDisplay As String
strDisplay = ""

For I = 1 To txtDisp_Number.Text
For K = 1 To I
strDisplay = strDisplay & I & vbTab
Next
strDisplay = strDisplay & vbCrLf
Next Annamalai University
MsgBox strDisplay
End Sub
Private Sub cmdExit_Click()
Unload Me
End Sub
Private Sub Form_Load()
Me.Top = 0
Me.Left = 0
txtDisp_Number.Text = 5
End Sub

Page 1
Visual Programming

Private Sub txtDisp_Number_LostFocus()


If IsNumeric(txtDisp_Number.Text) Then
If txtDisp_Number.Text > 16 Then
MsgBox "Enter a valid range between 1 and 16"
txtDisp_Number.Text = 5
End If
End If
End Sub

2: Enter a string and check if it is a palindrome.

Solution:

Form Layout

Option Explicit
Private Sub cmdCheck_Click()
Dim lngLength As Long, strRevString As String, strPalindText As String, I As
Integer
strRevString = ""
lngLength = Len(Trim(txtPalind_Text.Text))
strPalindText = UCase(Trim(txtPalind_Text.Text))

If lngLength = 0 Then
Exit Sub
End If

For I = lngLength To 1 Step -1


strRevString = strRevString & Mid(strPalindText, I, 1)
Next Annamalai University
If strPalindText = strRevString Then
MsgBox "The given text is a Palindrome"
Else
MsgBox "The given text is NOT a Palindrome"
End If
txtPalind_Text.Text = ""
txtPalind_Text.SetFocus
End Sub
Private Sub cmdExit_Click()

Page 2
Visual Programming

Unload Me
End Sub
Private Sub Form_Load()
Me.Top = 0
Me.Left = 0

txtPalind_Text.Text = ""
End Sub

3: Design a form and display the Height and Width accordingly when it is resized.

Solution:

Form Layout:

Dim lngWidth As Long, lngHeight As Long, lngShape1Width As Long,


lngShape2Width As Long, lngShape1Height As Long, lngShape2Height As Long
Private Sub Form_Load()
Me.Top = 0
Me.Left = 0
lngWidth = Me.Width
Annamalai University
lngHeight = Me.Height
lblArea.Visible = False

Me.Width = 5745
Me.Height = 3900

lngWidth = Me.Width
lngHeight = Me.Height

Shape1.Left = Me.Width
Shape1.Top = Me.Top

Page 3
Visual Programming

'Shape1.Visible = False

Shape2.Left = Me.Left
Shape2.Top = Me.Height
'Shape2.Visible = False

End Sub
Private Sub Form_Resize()
Dim newWidth As Long, newHeight As Long
newWidth = Me.Width
newHeight = Me.Height

lngShape1Width = Shape1.Width
lngShape1Height = Shape1.Height

lngShape2Width = Shape2.Width
lngShape2Height = Shape2.Height

If lngWidth <> newWidth Then


lblArea.Visible = True
lblArea.WordWrap = True
lblArea.Caption = "New extended Width is : " + CStr(Abs(newWidth -
lngWidth)) & vbCrLf & _
"New extended Height is : " + CStr(Abs(newHeight - lngHeight))
End If

Shape1.Width = CStr(Abs((newWidth - Shape1.Left)))


Shape1.Height = Me.Height
Shape1.BackColor = RGB(100, 0, 225)

Shape2.Width = Me.Width
Shape2.Height = CStr(Abs(newHeight - Shape2.Top))
Shape2.BackColor = RGB(100, 0, 225)

End Sub

Annamalai University

Page 4
Visual Programming

4. Enter a String for Company Name and Change the Label text with the input string
user User Control.

Solution:

FormLayout

Private Sub cmdChange_Click()


If Trim(txtCompany_Name.Text) = "" Then
Exit Sub
End If
Me.UserControl11.Comp_Name = txtCompany_Name.Text
End Sub
Private Sub cmdExit_Click()
Unload Me
End Sub
Private Sub Form_Load()
Me.Top = 0
Me.Left = 0

Me.UserControl11.Comp_Name = "Test Company Name"


End Sub

5. Explain the use of Listbox. Enter Values into a Textbox and add the contents to a
lsitbox. Select items from Listbox 1 and move to Listbox 2.

Solution:

FormLayout
Annamalai University

Page 5
Visual Programming

Option Explicit
Private Sub cmdAdd_Click()
If Len(Trim(txtNewItem.Text)) = 0 Then
Exit Sub
End If
lstLHSItems.AddItem Trim(txtNewItem.Text)
txtNewItem.Text = ""
txtNewItem.SetFocus
End Sub
Private Sub cmdAddAll_Click()
If lstLHSItems.ListCount = 0 Then
Exit Sub
End If
If lstLHSItems.ListIndex = -1 Then
lstLHSItems.ListIndex = 0
End If
Dim I As Integer
For I = 0 To (lstLHSItems.ListCount - 1)
lstLHSItems.ListIndex = 0
lstRHSItems.AddItem lstLHSItems.List(0)
lstLHSItems.RemoveItem (0)
Next
End Sub
Private Sub cmdAddOne_Click()
If lstLHSItems.ListCount = 0 Then
Exit Sub
End If
If lstLHSItems.ListIndex = -1 Then
lstLHSItems.ListIndex = 0
End If
lstRHSItems.AddItem lstLHSItems.List(lstLHSItems.ListIndex)
lstLHSItems.RemoveItem lstLHSItems.ListIndex
End Sub
Private Sub cmdExit_Click()
Unload Me
End Sub Annamalai University
Private Sub cmdRemAll_Click()
If lstRHSItems.ListCount = 0 Then
Exit Sub
End If
If lstRHSItems.ListIndex = -1 Then
lstRHSItems.ListIndex = 0
End If
Dim I As Integer
For I = 0 To (lstRHSItems.ListCount - 1)

Page 6
Visual Programming

lstRHSItems.ListIndex = 0
lstLHSItems.AddItem lstRHSItems.List(0)
lstRHSItems.RemoveItem (0)
Next
End Sub
Private Sub cmdRemOne_Click()
If lstRHSItems.ListCount = 0 Then
Exit Sub
End If
If lstRHSItems.ListIndex = -1 Then
lstRHSItems.ListIndex = 0
End If
lstLHSItems.AddItem lstRHSItems.List(lstRHSItems.ListIndex)
lstRHSItems.RemoveItem lstRHSItems.ListIndex
End Sub
Private Sub Form_Load()
Me.Top = 0
Me.Left = 0
txtNewItem.Text = ""
End Sub
Private Sub txtNewItem_Change()
cmdAdd.Enabled = (Len(Trim(txtNewItem.Text)) > 0)
End Sub

6. Enter a filename in a textbox and search for the given file name in your System.

Solution:

FormLayout

Annamalai University

Page 7
Visual Programming

Option Explicit
Dim varPrimary As String, varSecondary As String, varPattern As String
Dim blnCancel As Boolean
Private Sub cmdClear_Click()
List1.Clear
txtFile_Pattern.Text = ""
txtFile_Pattern.SetFocus
End Sub
Private Sub cmdExit_Click()
Unload Me
End Sub
Private Sub cmdSearch_Click()
Dim FSO As New FileSystemObject
Dim varDrives As Drives, varDrive As Drive
Dim varFolders As Folders, varFolder As Folder
blnCancel = False

varPattern = Replace(Trim(txtFile_Pattern.Text), "*", "")


If InStr(varPattern, ".") > 1 Then
varPrimary = Trim(Mid(varPattern, 1, (InStr(varPattern, ".") - 1)))
varSecondary = Trim(Mid(varPattern, InStr(varPattern, ".")))
Else
varPrimary = Trim(varPattern)
End If

List1.Clear
Set varDrives = FSO.Drives
For Each varDrive In varDrives
If varDrive.IsReady And varDrive.DriveType = Fixed Then
Call SearchFiles(varDrive.RootFolder)
Call FolderSearch(varDrive.RootFolder)
End If
Next
End Sub
Private Sub SearchFiles(pFolder As Folder)
'If pFolder = Nothing Then Exit Sub
Annamalai University
On Error Resume Next
Dim varFiles As Files, varFile As File

If blnCancel Then Exit Sub


lblFileName.Caption = "Searching in Folder : " & pFolder.Path
Set varFiles = pFolder.Files
For Each varFile In varFiles
If Len(Trim(varPrimary)) > 0 And Len(Trim(varSecondary)) > 0 Then
If InStr(UCase(varFile.Name), UCase(varPrimary)) > 0 And
InStr(UCase(varFile.Name), UCase(varSecondary)) > 0 Then

Page 8
Visual Programming

List1.AddItem varFile.Path
End If
ElseIf Len(Trim(varPrimary)) > 0 And Len(Trim(varSecondary)) = 0 Then
If InStr(UCase(varFile.Name), UCase(varPrimary)) > 0 Then
List1.AddItem varFile.Path
End If
ElseIf Len(Trim(varPrimary)) = 0 And Len(Trim(varSecondary)) > 0 Then
If InStr(UCase(varFile.Name), UCase(varSecondary)) > 0 Then
List1.AddItem varFile.Path
End If
End If
Next
End Sub
Private Sub FolderSearch(pFolder As Folder)
On Error Resume Next
Dim varMyFolder As Folder
Dim varMyFolders As Folders

If blnCancel Then Exit Sub

DoEvents
Set varMyFolders = pFolder.SubFolders
For Each varMyFolder In varMyFolders
lblFileName.Caption = "Searching in Folder : " & varMyFolder.Path
Call SearchFiles(varMyFolder)
Call FolderSearch(varMyFolder)
Next
End Sub
Private Sub Command1_Click()
blnCancel = True
Call cmdClear_Click
End Sub
Private Sub Form_Load()
Me.Top = 0
Me.Left = 0
End Sub
Annamalai University
7. Design a form using MSFlexgrid and display details according to the product
chosen from combobox. Use ADO control for database connection.

Solution:

FormLayout

Page 9
Visual Programming

Option Explicit
Dim arrProduct() As String
Dim cnConn As New ADODB.Connection

Private Sub cmbProductName_Change()

End Sub

Private Sub cmdExit_Click()


Unload Me
End Sub
Private Sub cmdView_Click()
If cmbProductName.ListIndex = -1 Then Exit Sub
If Not Fetch_Product_Details Then Exit Sub
End Sub
Private Sub Form_Activate()
If Not Populate_Combo Then
Unload Me
Exit Sub
End If
End Sub
Private Sub Form_Load()
Me.Top = 0
Me.Left = 0

Annamalai University
Dim strConnection As String
If cnConn.State = 1 Then cnConn.Close
strConnection = "Provider=Microsoft.Jet.OLEDB.4.0; " & _
"Data Source = MscIT.mdb;" & _
"Persist Security Info=False"
cnConn.ConnectionString = strConnection
cnConn.Open
Me.Show
End Sub
Private Function Populate_Combo() As Boolean
Dim rsProduct As New ADODB.Recordset

Page 10
Visual Programming

Dim strSql As String, intRecCount As Integer


rsProduct.CursorLocation = adUseClient

strSql = "SELECT Product_ID, Product_Name FROM Product "


rsProduct.Open strSql, cnConn, adOpenKeyset, adLockBatchOptimistic
If rsProduct.EOF Then
MsgBox "Product details not defined! Cannot proceed!"
Populate_Combo = False
Exit Function
End If

intRecCount = rsProduct.RecordCount
ReDim arrProduct(intRecCount) As String
Dim I As Integer
While Not rsProduct.EOF
cmbProductName.AddItem rsProduct.Fields("Product_Name")
arrProduct(I) = rsProduct.Fields("Product_ID")
I=I+1
rsProduct.MoveNext
Wend
cmbProductName.ListIndex = 0

Populate_Combo = True
rsProduct.Close
Set rsProduct = Nothing
End Function
Private Function Fetch_Product_Details() As Boolean
Dim rsSaleDetails As New ADODB.Recordset
Dim strSql As String, I As Integer, J As Integer
rsSaleDetails.CursorLocation = adUseClient

strSql = "SELECT B.Product_Name, Format(A.Invoice_Date,'dd-MM-yyyy') AS


Invoice_Date, " & _
" A.Invoice_Number, A.Customer_Name, A.Quantity, A.Price, " & _
" (A.Quantity * A.Price) AS Prod_Value " & _
" FROM SALES A INNER JOIN Product B " & _
Annamalai University
" ON A.Product_ID = B.Product_ID " & _
" WHERE A.Product_ID = " & arrProduct(cmbProductName.ListIndex)

rsSaleDetails.Open strSql, cnConn, adOpenKeyset, adLockBatchOptimistic

If rsSaleDetails.EOF Then
MsgBox "Sales details not exist for this Product"
rsSaleDetails.Close
Set rsSaleDetails = Nothing
Fetch_Product_Details = False

Page 11
Visual Programming

Exit Function
End If

rsSaleDetails.MoveFirst
MSFlexGrid1.Clear
MSFlexGrid1.Rows = rsSaleDetails.RecordCount
While Not rsSaleDetails.EOF
MSFlexGrid1.Row = I
For J = 0 To (rsSaleDetails.Fields.Count - 1)
MSFlexGrid1.Col = J
MSFlexGrid1.Text = rsSaleDetails.Fields(J)
Next
I=I+1
rsSaleDetails.MoveNext
Wend

Fetch_Product_Details = True
End Function

8. Create a Form layout as follows:

When pressed ‘1’, Sunday should be messaged. Similarly, for 2: Monday, 3:


Annamalai University
Tuesday, 4: Wednesday, 5: Thursday, 6: Friday and finally for 7: Saturday.

Solution:

The Property Table:

Object Property Setting


Textbox Name T1
CommandButton Name D1

Page 12
Visual Programming

In the Day Button Click Event the Code is:

Private Sub D1_Click()


Select Case Val(T1.Text)
Case 1
MsgBox " The Day is Sunday"
Case 2
MsgBox " The Day is Monday"
Case 3
MsgBox " The Day is Tuesday"
Case 4
MsgBox " The Day is Wednesday"
Case 5
MsgBox " The Day is Thursday"
Case 6
MsgBox " The Day is Friday"
Case 7
MsgBox " The Day is Saturday"
End Select
End Sub

9. Create a form that should display the text “Welcome to visual basic lab” when
clicked on the Display button and when clicked on the clear button should clear
the text in the text box and when clicked on the exit button should exit the form.

Annamalai University

Solution:

The properties table of the welcome program.

Page 13
Visual Programming

Object property settings


Form Name frmwelcome
Caption The Welcome program
CommandButton Name CmdExit
Caption E&xit
CommandButton Name Cmdclear
Caption &clear
CommandButton Name Cmddisplay
Caption &display
Textbox Name txtdisplay
Multiline True
In the Exit button’s click event write the following code
Private sub cmdexit_click ()
End sub

In the Display button’s click event write the following code


Private sub cmddisplay_click ()
Txtdisplay.text = “Welcome to Visual Basic Lab”
End sub

In the Clear button’s click event write the following code


Private sub cmdclear_click ()
Txtdisplay.text = “ “
End sub

10. Write a Program to input two Numbers and Find its sum, multiplication,
subtraction, division and modulus.

Annamalai University

Page 14
Visual Programming

Solution:
Create form layout add three Text Box and Four Command Button as Specified
The Property Table:

Object Property Setting


Textbox1 Name T1
Textbox2 Name T2
Textbox3 Name T3
CommandButton1 Name C1

Caption ADD
CommandButton2 Name C2

Caption SUB
CommandButton3 Name C3

Caption MUL
CommandButton4 Name C4

Caption DIV
CommandButton5 Name C5

Caption MOD

The Code is:


Private Sub C1_Click()
T3.Text = Val(T1) + Val(T2)
End Sub
Private Sub C2_Click()
T3.Text = Val(T1) - Val(T2)
End Sub
Private Sub C3_Click()
Annamalai University
T3.Text = Val(T1) * Val(T2)
End Sub
Private Sub C4_Click()
T3.Text = Val(T1) / Val(T2)
End Sub
Private Sub C5_Click()
T3.Text = Val(T1) Mod Val(T2)
End Sub

Page 15
Visual Programming

Visual C++
1. Create Text Output in a window and Repainting.

Solution:

1. Click on the StartProgramsMicrosoft Visual Studio 6.0


2. Click on the Microsoft Visual C++
3. Next click on the File New from the menu bar
4. Select the Win32 Application form Projects tab.
5. Type the project name as Repainting in the project name text box.
6. Click on the OK button.

Annamalai University
7. Select the An empty Project option.
8. Finally click on the Finish button.
9. Click on OK button.

Now we will and C++ Source files to the project.

10. Next click on the File New from the menu bar
11. Select the C++ Source file from Files tab
12. Type the Repainting as the file name in the File name text box.

Page 16
Visual Programming

Type the Code the below code to the .cpp file:

//--> Handle Left mouse button click to get positon for displaying
// the text "Hello World"

//--> Add Message map for WM_PAINT to repaint the text whenever
// your window gets repainted.

#include <AfxWin.h>

//Frame Window
class CMainFrame : public CFrameWnd
{
public:
CPoint pt;
CMainFrame()
{
Create(0,"My
window",WS_OVERLAPPEDWINDOW,CRect(10,10,500,500),NULL,NULL,0,NULL);
pt.x=0;
pt.y=0;
}
void OnLButtonDown(UINT nFlags,CPoint point)
{
//MessageBox("Message Handled for Left Mouse button");
pt = point;
Invalidate(TRUE);
}
void OnPaint()
{
CPaintDC dc(this);
dc.TextOut(pt.x,pt.y,"Hello");
}
DECLARE_MESSAGE_MAP()
}; Annamalai University
//For handling messages
BEGIN_MESSAGE_MAP(CMainFrame,CFrameWnd)
ON_WM_LBUTTONDOWN()
ON_WM_PAINT()
END_MESSAGE_MAP()
//For handling messages

Page 17
Visual Programming

//Application Class
class CMyApp : public CWinApp
{
public:

BOOL InitInstance()
{
m_pMainWnd = new CMainFrame;
m_pMainWnd->ShowWindow(SW_SHOWNORMAL);
return TRUE;
}
};
//Application Class

//Global object for Application


CMyApp theApp;

Note: Before Executing you have to add the MFC Dll to the project.

13. Click on the Project  Settings


14. Select the Use MFC in Shared DLL Microsoft Foundation Classes dropdown list
box.
15. Click on OK button.
16. Click on Build Execute Repainting.exe

Output:

Annamalai University

Tip: You can move the mouse around the window and click anywhere the word hello
world will be displayed that particular position. Even if you minimize and maximize the
window also the text will not erase. Because it will automatically repaint the text.

Page 18
Visual Programming

2. Create Scrollbars with Message handlers.

Solution:

1. Click on the StartProgramsMicrosoft Visual Studio 6.0


2. Click on the Microsoft Visual C++
3. Next click on the File New from the menu bar
4. Select the Win32 Application form Projects tab.
5. Type the project name as Scrollbars in the project name text box.
6. Click on the OK button.

Figure 4.1

Annamalai University
7. Select the An empty Project option.
8. Finally click on the Finish button.
9. Click on OK button.

Now we will and C++ Source files to the project.

10. Next click on the File New from the menu bar
11. Select the C++ Source file from Files tab
12. Type the Scrollbars as the file name in the File name text box.

Type the Code the below code to the .cpp file:

Page 19
Visual Programming

// To get scroll bars add WS_HSCROLL,WS_VSCROLL in the Style,


// while creating the window ["Create" function in CMainFrame constructor]

//Add Message handle to handle Vertical scroll and Horizontal scroll bar.
// ON_WM_HSCROLL()
// ON_WM_VSCROLL()

#include <AfxWin.h>

//Frame Window
class CMainFrame : public CFrameWnd
{
public:

CMainFrame();
void OnHScroll(UINT nSBCode,UINT nPos,CScrollBar *pScrollBar);
void OnVScroll(UINT nSBCode,UINT nPos,CScrollBar *pScrollBar);
DECLARE_MESSAGE_MAP()
};

//For handling messages


BEGIN_MESSAGE_MAP(CMainFrame,CFrameWnd)
ON_WM_HSCROLL()
ON_WM_VSCROLL()
END_MESSAGE_MAP()
//For handling messages

CMainFrame::CMainFrame()
{
Create(0,"My
window",WS_OVERLAPPEDWINDOW|WS_HSCROLL|WS_VSCROLL,
CRect(10,10,500,500),NULL,NULL,0,NULL);
}
Annamalai University
//Horizontal Scrollbar
void CMainFrame::OnHScroll(UINT nSBCode,UINT nPos,CScrollBar
*pScrollBar)
{
switch(nSBCode)
{
case SB_LINELEFT:
MessageBox("Left");
break;

Page 20
Visual Programming

case SB_LINERIGHT:
MessageBox("Right");
break;
case SB_PAGELEFT:
MessageBox("Page Left");
break;
case SB_PAGERIGHT:
MessageBox("Page Right");
break;
case SB_THUMBPOSITION:
MessageBox("Thumb");
break;
};
}
//Horizontal Scrollbar

//Vertical Scrollbar
void CMainFrame::OnVScroll(UINT nSBCode,UINT nPos,CScrollBar
*pScrollBar)
{
switch(nSBCode)
{
case SB_LINELEFT:
MessageBox("Left");
break;
case SB_LINERIGHT:
MessageBox("Right");
break;
case SB_PAGELEFT:
MessageBox("Page Left");
break;
case SB_PAGERIGHT:
MessageBox("Page Right");
break;
case SB_THUMBPOSITION:
MessageBox("Thumb");

};
Annamalai University
break;

}
//Vertical Scrollbar

//Application Class
class CMyApp : public CWinApp
{
public:

Page 21
Visual Programming

BOOL InitInstance()
{
m_pMainWnd = new CMainFrame;
m_pMainWnd->ShowWindow(SW_SHOWNORMAL);
return TRUE;
}
};
//Application Class

//Global object for Application


CMyApp theApp;

Note: Before Executing you have to add the MFC Dll to the project.

13. Click on the Project  Settings


14. Select the Use MFC in Shared DLL Microsoft Foundation Classes dropdown list
box.
15. Click on OK button.
16. Click on Build Execute Scrollbars.exe

Output:

Annamalai University

Figure 4.2

(Click on the Scroll bars to get the message handlers)

Page 22
Visual Programming

3. Create Basic Drawing with Lines and Fill Regions with colors.

Solution:

17. Click on the StartProgramsMicrosoft Visual Studio 6.0


18. Click on the Microsoft Visual C++
19. Next click on the File New from the menu bar
20. Select the Win32 Application form Projects tab.
21. Type the project name as Basic Drawing in the project name text box.
22. Click on the OK button.

Figure 5.1

23. Select the An empty Project option.


Annamalai University
24. Finally click on the Finish button.
25. Click on OK button.

Now we will and C++ Source files to the project.

26. Next click on the File New from the menu bar
27. Select the C++ Source file from Files tab
28. Type the Basic Drawing as the file name in the File name text box.

Type the Code the below code to the .cpp file:

Page 23
Visual Programming

//--> Get start point and end point to draw line.


//--> Program uses "bStart" bool variable to differentiate between
// first and next click.

//--> To Draw line set pen style as PS_SOLID.[OnLButtonDown Function]

//--> To draw Dots set pen style as PS_DOT.[OnLButtonDown Function]

//--> To fill region when Right Mouse button pressed.

#include <AfxWin.h>

//Frame Window
class CMainFrame : public CFrameWnd
{
public:
CPoint pt;
bool bStart;

public:
CMainFrame();
void OnLButtonDown(UINT nFlags,CPoint point);
void OnRButtonDown(UINT nFlags,CPoint point);
DECLARE_MESSAGE_MAP()
};

//For handling messages


BEGIN_MESSAGE_MAP(CMainFrame,CFrameWnd)
ON_WM_LBUTTONDOWN()
ON_WM_RBUTTONDOWN()
END_MESSAGE_MAP()
//For handling messages

CMainFrame::CMainFrame()
{ Annamalai University
Create(0,"My
window",WS_OVERLAPPEDWINDOW,CRect(10,10,500,500),NULL,NULL,0,NULL);
bStart = true;
pt.x=0;
pt.y=0;
}
void CMainFrame::OnLButtonDown(UINT nFlags,CPoint point)
{
if(!bStart)

Page 24
Visual Programming

{
CClientDC dc(this);

//Create appropriate pen


CPen pen;
pen.CreatePen(PS_SOLID,1,RGB(0,0,0));

//Select pen to Device context


CPen *OldPen = dc.SelectObject(&pen);

//Draw Line
dc.MoveTo(pt);
dc.LineTo(point);

//Restore old Pen


dc.SelectObject(OldPen);

}
else
pt = point;

bStart = !bStart;
//Invalidate(TRUE);
}

void CMainFrame::OnRButtonDown(UINT nFlags,CPoint point)


{

CClientDC dc(this);

//Create brush
CBrush brush;
brush.CreateSolidBrush(RGB(255,0,0));

//Select brush to device context.


CBrush *OldBrush = dc.SelectObject(&brush);
Annamalai University
//Fill the region
dc.FloodFill(point.x,point.y,RGB(0,0,0));

//Restore OldBrush
dc.SelectObject(OldBrush);

//Application Class

Page 25
Visual Programming

class CMyApp : public CWinApp


{
public:

BOOL InitInstance()
{
m_pMainWnd = new CMainFrame;
m_pMainWnd->ShowWindow(SW_SHOWNORMAL);
return TRUE;
}
};
//Application Class

Note: Before Executing you have to add the MFC Dll to the project.

29. Click on the Project  Settings


30. Select the Use MFC in Shared DLL Microsoft Foundation Classes dropdown list
box.
31. Click on OK button.
32. Click on Build Execute Basic Drawing.exe

Output:

Annamalai University

(Click inside the window automatically start and end point will be joined with line and
right click inside the area automatically red color filled with the closed area.)

Page 26
Visual Programming

4. Writing a program for Keyboard Events.

Solution:

1. Click on the StartProgramsMicrosoft Visual Studio 6.0


2. Click on the Microsoft Visual C++
3. Next click on the File New from the menu bar
4. Select the Win32 Application form Projects tab.
5. Type the project name as KeyEvents in the project name text box.
6. Click on the OK button.

7. Select the An empty Project option.


Annamalai University
8. Finally click on the Finish button.
9. Click on OK button.

Now we will and C++ Source files to the project.

10. Next click on the File New from the menu bar
11. Select the C++ Source file from Files tab
12. Type the KeyEvents as the file name in the File name text box.

Page 27
Visual Programming

Type the Code the below code to the .cpp file:


// Keystorkes Messages handling using WM_KEYDOWN and WM_KEYUP

#include <AfxWin.h>

//Frame Window
class CMainFrame : public CFrameWnd
{
public:

public:
CMainFrame();
void OnKeyDown(UINT nChar,UINT nRepCnt,UINT nFlags);
void OnKeyUp(UINT nChar,UINT nRepCnt,UINT nFlags);
DECLARE_MESSAGE_MAP()
};

//For handling messages


BEGIN_MESSAGE_MAP(CMainFrame,CFrameWnd)
ON_WM_KEYDOWN()
ON_WM_KEYUP()
END_MESSAGE_MAP()
//For handling messages

CMainFrame::CMainFrame()
{
Create(0,"My
window",WS_OVERLAPPEDWINDOW,CRect(10,10,500,500),NULL,NULL,0,NULL);
}
void CMainFrame::OnKeyDown(UINT nChar,UINT nRepCnt,UINT nFlags)
{
MessageBox("Key Down");
}

Annamalai University
void CMainFrame::OnKeyUp(UINT nChar,UINT nRepCnt,UINT nFlags)
{
MessageBox("Key Up");
}

//Application Class
class CMyApp : public CWinApp
{
public:

Page 28
Visual Programming

BOOL InitInstance()
{
m_pMainWnd = new CMainFrame;
m_pMainWnd->ShowWindow(SW_SHOWNORMAL);
return TRUE;
}
};
//Application Class

//Global object for Application


CMyApp theApp;

Note: Before Executing you have to add the MFC Dll to the project.

13. Click on the Project  Settings


14. Select the Use MFC in Shared DLL Microsoft Foundation Classes dropdown list
box.
15. Click on OK button.
16. Click on Build Execute KeyEvents.exe

Output:

Annamalai University

(Press the any key in the keyboard to get the message)

Page 29
Visual Programming

5. Writing a program Toolbars and Menu

Solution:

We create the Workspace for Menu and Toolbars.


Now we will learn how to add resources

1. Next click on the File New from the menu bar


2. Next click on Files tab
3. Select the Resource Scripts form Files tab.
4. Type the project name as RScript in the project name text box.
5. Click on the OK button.

Annamalai University
8. Next click on the Insert  Resource
9. Select Menu from the Resource Dialog box
10. Click on the OK button

Page 30
Visual Programming

Annamalai University

11. Click on the 1st Item and type File in the Caption text box

Page 31
Visual Programming

Figure 9.4

1. Again type “ID_FILE_SAYHELLO”


2. Now Choose Project Add To Project File
3. Then select "Resource.h" to your workspace.
4. include the "Resource.h" file to the .cpp file.

Figure 9.5

5. Now we will add the Icon


6. Click on the Insert  Resource New
7. Using Paint Bucket Fill the color “Green”
8. Type the text using Text Tool “V++”

Annamalai University

Page 32
Visual Programming

#include <AfxWin.h>
#include "Resource.h"

//Frame Window
class CMainFrame : public CFrameWnd
{
public:
HCURSOR hCursor;
public:
Annamalai University
CMainFrame();
void OnSayHello();
void OnSetMyIcon();
DECLARE_MESSAGE_MAP()
};

//For handling messages


BEGIN_MESSAGE_MAP(CMainFrame,CFrameWnd)
ON_COMMAND(ID_FILE_SAYHELLO,OnSayHello)
ON_COMMAND(ID_FILE_ICON,OnSetMyIcon)

Page 33
Visual Programming

END_MESSAGE_MAP()
//For handling messages

CMainFrame::CMainFrame()
{
Create(0,"My
window",WS_OVERLAPPEDWINDOW,CRect(10,10,500,500),NULL,
MAKEINTRESOURCE(IDR_MYMENU),0,NULL);
}
void CMainFrame::OnSayHello()
{
MessageBox("Hello");
}
void CMainFrame::OnSetMyIcon()
{
HICON hIcon;
hIcon=
LoadIcon(AfxGetInstanceHandle(),MAKEINTRESOURCE(IDI_MYICON));
SetIcon(hIcon,FALSE);
}

//Application Class
class CMyApp : public CWinApp
{
public:

BOOL InitInstance()
{
m_pMainWnd = new CMainFrame;
m_pMainWnd->ShowWindow(SW_SHOWNORMAL);
return TRUE;
}
};
//Application Class

Annamalai University
//Global object for Application
CMyApp theApp;

17. Click on the Project  Settings


18. Select the Use MFC in Shared DLL Microsoft Foundation Classes dropdown list
box.
19. Click on OK button.
20. Click on Build Execute Menu ToolBar.exe

Page 34
Visual Programming

Output: Click on the File  Hello

Click on the File  Icon (window icon changed)

Annamalai University
6. Viewing the Database Records using - DAO

1. Create SDI application, select FileNewProject


2. Then choose MFC AppWizard (exe) from the list.
3. Type the name for the Application then click OK button..
4. Select the Single Document in step 1/6.

Page 35
Visual Programming

5. In step 2 / 6 select Database view without file support. Since this program does not
require file support.

Then choose Data source option to select data source for this
application.

Annamalai University

6. Then press the OK button.

Page 36
Visual Programming

7. The dialog box showing the tables available in the database, choose one Table
(Authors) in that.
8. Press the OK button.

9. Finally, press Finish.


10. A form is created by Appwizard,
11. Now add Edit control for all the required fields
in the table as shown below:

12. Next we will associate the fields with the database’s table ,
13. Click on ViewClass Wizard
Annamalai University
14. Click on Member Variables tab.
15. Then associated each Edit control

Page 37
Visual Programming

16. When the application executed the interface look like below:

Annamalai University
17. Record Navigation can be made using the Navigation Symbols provided in the
toolbar.
Creating ActiveX control

1. Create SDI Application choose FileNewProjects


2. Choose MFC ActiveX Control Wizard in the list.
3. Press OK by giving Project name SampleActiveX for the ActiveX control.

Page 38
Visual Programming

4. To display a text in the activex control.

Select CSampleActiveXCtrl class’s onDraw function in our example

Write the code below to display Welcome text

void CSampleActiveXCtrl::OnDraw(
CDC* pdc, const CRect& rcBounds, const CRect& rcInvalid)
{
pdc->FillRect(rcBounds,
CBrush::FromHandle((HBRUSH)GetStockObject(WHITE_BRUSH)));
pdc->Ellipse(rcBounds);

//Add this code Annamalai University


pdc->TextOut(0,0,"ActiveX Demo");
}
4. Now build the SampleActivex.ocx file will be generated in the output directory.

Page 39
Visual Programming

Exercise:

Visual Basic

1. Write an event procedure to find the sum of numbers from 1 to the selected value.
Use a horizontal scroll bar to set the maximum value.

2. Write a function procedure

a. To find the power of a number.


b. To convert the temperature in Fahrenheit into Celsius

3. Using MouseDown event, write a Visual Basic application to identify whether the
right button or the left button was clicked .

4. Railways needs to validate the date of travel for the reservation facility .The
booking should be either on that current day or for the next 15 days . How could
we implement this in Visual Basic?

5. Load a BMP file in the OLE control and modify it at run time to illustrate that
Visual Basic program can be used as a front-end application

Visual C++

1. Create a Window using C++ Source files?


2. Create Application for user can draw rectangle and save the rectangle to a file and
retrieve the rectangle when the file opened.
3. Create Document-View-Frame-Menu using AppWizard.
4. Create Toolbars and Status bars
5. Write a program for Mouse Events.

Annamalai University

Page 40

You might also like