Saturday, 10 November 2012

CALCULATOR


 1. Design the form.
2. Create a command Button named as a Command1 and copy that and paste it 10 times. This will create a control array.
3. Create a cmdoperator control array using another Command Button named as Command2.
4. Place Command Button named as Command3 and set its caption to ‘clear’.
5. Place Command Button named as Command4 and set its caption to ‘=’.
6. place a Textbox for the Display.
 DESIGN VIEW:
 
 
CODING:
Private lastoperator As String
Private firstpart As String

Private Sub Form_Load()
TxtResult.Enabled = False
Me.KeyPreview = True
End Sub

Private Sub Form_KeyDown(KeyCode As Integer, Shift As Integer)
'number in main keyboard
If (KeyCode >= 48 And KeyCode <= 57) Then
addDigits (Chr(KeyCode))
End If
'numbers in numpad
If (KeyCode >= 96 And KeyCode <= 105) Then
addDigits (Chr(KeyCode - 48))
End If
'if backspace
If (KeyCode = 8) Then
If (TxtResult.Text <> "") Then
TxtResult.Text = Left(TxtResult.Text, Len(TxtResult.Text) - 1)
End If
End If
'for various operators
If (KeyCode = 111) Then registerOperator ("/")
If (KeyCode = 106) Then registerOperator ("*")
If (KeyCode = 109) Then registerOperator ("-")
If (KeyCode = 107) Then registerOperator ("+")
End Sub

Private Sub cmdoperator_Click(Index As Integer)
registerOperator (cmdoperator(Index).Caption)
End Sub

Private Sub cmdclear_Click()
firstpart = ""
lastoperator = ""
TxtResult.Text = ""
End Sub
 
Private Sub Cmdequals_Click()
Select Case lastoperator
Case Is = "+"
TxtResult.Text = firstpart - TxtResult.Text + TxtResult.Text + TxtResult.Text
Case Is = "-"
TxtResult.Text = firstpart - TxtResult.Text
Case Is = "/"
TxtResult.Text = firstpart / TxtResult.Text
Case Is = "*"
TxtResult.Text = firstpart * TxtResult.Text
End Select
firstpart = ""
lastoperator = ""
End Sub

Private Sub Command1_Click(Index As Integer)
addDigits (Command1(Index).Caption)
End Sub

Private Sub addDigits(Digit As String)
TxtResult.Text = TxtResult.Text & Digit
End Sub

Private Sub registerOperator(Operatortext As String)
lastoperator = Operatortext
firstpart = TxtResult.Text
TxtResult.Text = ""
End Sub
 
OUTPUT: