Handling Keyboard Events

  • Similar to mouse events even the keyboard events can be handled
    The following example shows some of the keyboard events. The Following example also validates the TextBox controls of the form (Shown in Fig. 7 and Fig. 8).
Public Class Form1
Private Sub TextBox1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TextBox1.KeyDown
TextBox2.Text = e.KeyCode ' used to get the ASCII code
MessageBox.Show(e.KeyCode.ToString())
End Sub
Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
If Char.IsDigit(e.KeyChar) = True Then
MessageBox.Show("You pressed a number key")
End If
End Sub
Private Sub TextBox1_Validating(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles TextBox1.Validating
'becuase of this routine the focus will be here and button 'click event does not have any affect ......
If TextBox1.Text = "" Then
e.Cancel = True
End If
End Sub

Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
TextBox1.BackColo
r = System.Drawing.Color.White
End Sub Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim aControl As System.Windows.Forms.Control
'Loops through each control on the form
For Each aControl In Me.Controls
'check to see if the control being considered is a
'textbox and it contains an empty string
If TypeOf aControl Is TextBox AndAlso
aControl.Text= "" Then
' if the text box does not contain string then it
'is given focus and method is exited
aControl.Focus()
aControl.BackColor = System.Drawing.Color.Red
Beep()
MessageBox.Show("All entries are not made ")
Exit Sub
End If
Next
MessageBox.Show("All entries are made")
End Sub
Private Sub TextBox2_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox2.TextChanged
TextBox2.BackColor = System.Drawing.Color.White
End Sub

Private Sub TextBox3_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox3.TextChanged TextBox3.BackColor = System.Drawing.Color.White End Sub
Private Sub TextBox4_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox4.TextChanged
TextBox4.BackColor = System.Drawing.Color.White
End Sub
End Class




Mouse Event<< Previous

Next >> Data Access with ADO.net

Our aim is to provide information to the knowledge seekers. 


comments powered by Disqus
Footer1