-
Hi everyone!
I am actually building a calculator in VB; actually the program is implemented only by mouse events, but i'd like to add keyboard support; for example, if the user presses the "9" button on the keyboard, then the program calls the number9MousePressed Sub.
I also want to implement it without changing all buttons' code; how can i do that?
Thnks
Alessandro
-
First you got to set the form.keyprewiew property to Ture and then you add code that call the desired functions in the form_KeyPress Event
-
take a look at the calc.vbp sample supplied with vb
if you add TrapKey KeyCode to just about every keydown event on the form
this lot might give you some clues what to do!
Code:
Private Sub Number_KeyDown(Index As Integer, KeyCode As Integer, Shift As Integer)
TrapKey KeyCode
End Sub
Private Sub TrapKey(KeyCode As Integer)
Select Case KeyCode
Case 96 To 105
Number_Click KeyCode - 96
Case 106
'*
Operator_Click 2
Case 107
'+
Operator_Click 1
Case 109
'-
Operator_Click 3
Case 111
'/
Operator_Click 0
Case Else
'put extra cases for backspace etc
Debug.Print KeyCode
End Select
End Sub
-
Thanks!
-
Ops...
That's ok but... why does it write two times the number when i press a key in the keyboard? Here's the way i used to implemented number 9; i'll make a Case-Switch selection later. Do i look like a newbie, don't I? ;-)
Private Sub Form_KeyPress(KeyAscii As Integer)
If KeyAscii = 57 Then
number9_Click
End If
End Sub
-
do you mean that it writes 99 instead of 9 when you press the nr 9 key.
If your using a TextBox to display the numbers then you dont need the keypress event as long as the textbox got focus. On the other hand It could be a good idea to check that its a number being written.
ex
Private Sub Text1_KeyPress(KeyAscii As Integer)
Print KeyAscii
Select Case KeyAscii
Case 42 ' *
Case 43 ' +
Case 44 ' ,
Case 45 ' -
Case 46 ' .
Case 47 ' /
Case 48 To 57 ' nr 0-9
Case Else
KeyAscii = 0
End Select
End Sub
good luck!
-
First thing to do would be to put a break point next to the line Private Sub Form_KeyPress(KeyAscii As Integer) and see if the event is being fired twice for some reason