'------------------------------------------------------------------------ ' T R A P P I N G K E Y S T R O K E S ' For Data Input and Functionality ' Ron Kessler '------------------------------------------------------------------------ 'Updated 8/2/06 for C# 2005 'This app shows you how to trap any keystroke and make it do what you want! 'It also shows how to validate user input by using the Keypress event of a textbox 'If you want, you can also make the ENTER key work like the TAB key. Look at the 'KeyDown event for the form. Option Explicit On Public Class frmMain Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click '---add them up If Trim(txtFirst.TabIndex) = "" Or Trim(txtSecond.Text) = "" Then MsgBox("Please enter a number") Else Try Dim firstNumber As Single Dim secondNumber As Single firstNumber = Trim(txtFirst.Text) secondNumber = Trim(txtSecond.Text) lblAnswer.Text = firstNumber + secondNumber Catch MessageBox.Show("An error occured while adding the numbers", "System Message", MessageBoxButtons.OK, MessageBoxIcon.Error) txtFirst.Focus() End Try End If End Sub Private Sub txtFirst_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtFirst.KeyPress '---the KeyPress event only responds to "character keys" like numbers/letters ' It will not respond to F10 or # keys, for instance. For those use the KeyDown or KeyUp events Select Case e.KeyChar Case "0" To "9", "." e.Handled = False 'was error handled? No because there is no error! Case ControlChars.Back e.Handled = False 'Case "a" To "z" 'for alpha characters ' e.Handled = False Case Else e.Handled = True 'was NOT handled because there is an error so pass it to O/S to handle End Select End Sub Private Sub txtSecond_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtSecond.KeyPress '---the KeyPress event only responds to "character keys" like numbers/letters ' It will not respond to F10 or # keys, for instance. For those use the KeyDown or KeyUp events Select Case e.KeyChar Case "0" To "9", "." e.Handled = False 'was error handled? No because there is no error! Case ControlChars.Back e.Handled = False 'Case "a" To "z" 'for alpha characters ' e.Handled = False Case Else e.Handled = True 'was NOT handled because there is an error so pass it to O/S to handle End Select End Sub Private Sub frmMain_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyUp '---to trap the enter key and make it work like the tab key you must set KeyPreview = True on the form properties If e.KeyCode = Keys.Enter Then e.Handled = True Me.ProcessTabKey(True) End If End Sub Private Sub btnEnd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEnd.Click Me.Close() End Sub End Class