vb.net 检测窗体上的按键

vb.net detect keypress on a form

我是 vb.net 的新手,正在尝试检测表单上的 KeyPress
我通过创建一个侦听器在 JavaFX 中完成了此操作,当按下 ESC 键时应用程序关闭
我没有在 vb.net
中找到任何使用侦听器的代码示例 我找到了处理 TextBox 的 KeyPress 的代码,但相同的代码处理 Form FAILS
对于这个从任何表单关闭应用程序的函数,我想知道它是否需要在模块中声明?虽然这部分问题很高兴知道称之为奖金
我的问题是为什么这段代码没有检测到 frmOne 上的按键?
在 txtBoxOne 中检测按键的代码按预期运行

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

结束Class

相同的代码将适用于表单,但如果子控件具有焦点,则默认情况下表单不会引发键盘事件。您需要将表单的 KeyPreview 属性 设置为 True,在这种情况下,表单将在活动子控件之前引发这些键盘事件。