Search code examples
vb.netkeypress

vb.net detect keypress on a form


I am new to vb.net and am trying to detect a KeyPress on a Form
I have accomplished this in JavaFX by creating a listener that when the ESC Key is press the application close
I have not found any code examples that use a listener in vb.net
I have found code that Handles a KeyPress for a TextBox but the same code for a Form FAILS
For this function to close the application from any Form I am wondering if it needs to be declared in a Module? While that part of the question would be nice to know Call it a Bonus
My question is why is this code not detecting a keypress on frmOne ?
The code to detect a keypress in the txtBoxOne runs as expected

Public Class frmOne
Private Sub frmOne_KeyPress(sender As Object, e As KeyPressEventArgs) Handles Me.KeyPress
    'frmOne Property FixedToolWindow
    'frmOne is the Start Up Form
    If Asc(e.KeyChar) > 1 Then
        MessageBox.Show("You Pressed " & e.KeyChar)
    End If
    'If Asc(e.KeyChar) > 1 Then txtBoxOne.Text = "You Pressed"
End Sub

Private Sub txtBoxOne_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs) Handles txtBoxOne.KeyPress
    If Asc(e.KeyChar) = 13 Then
        e.Handled = True
        MsgBox("Error.")
    Else
        e.Handled = False
    End If
End Sub
Private Sub btnToFormTwo_Click(sender As Object, e As EventArgs) Handles btnToFormTwo.Click
    Dim i As Integer
    i = txtBoxOne.Text.Length
    If i = 0 Then
        'txtBoxOne.Text = "Enter"
        MessageBox.Show("Enter Data")
        txtBoxOne.Select()
        Return
    End If
    Dim OBJ As New frmTwo
    OBJ.SPass = txtBoxOne.Text
    OBJ.Show()
    'MyTextBox_Enter()
    txtBoxOne.Clear()
    Me.Hide()
    'Me.Close()'R Click project PassVar Set Start Up Form
    'Best Solution is to have Splash Form as Start Up Form
End Sub
Public Sub MyTextBox_Enter()
    txtBoxOne.Clear()
End Sub
'Private Sub frmOne_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'Use code below if pre populated text in txtBoxOne
'Me.ActiveControl = txtBoxOne
'txtBoxOne.Select(txtBoxOne.Text.Length, 0)
'txtBoxOne.Select()

'End Sub

End Class


Solution

  • The same code will work for a form but a form will not raise keyboard events by default if a child control has focus. You need to set the form's KeyPreview property to True, in which case the form will raise those keyboard events before the active child control does.