首页 > 解决方案 > 用于调用特定按钮操作的特定键盘字符

问题描述

当我启动我的程序并按下指定的键来调用我的按钮命令时,它什么也不做。

焦点仍然在其中一个按钮上,没有任何反应。

我尝试了多种代码,从使用 KeyDown 到 KeyPress 到包含 vbKey 的代码。

我对 vb 很陌生,所以我很可能只是明白我在做什么。:(

Public Class Form1

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
    Me.KeyPreview = True
End Sub

Private Sub Form1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs)
    If e.KeyCode = "/" Then
        Call Button1_Click(sender, e)
    End If
End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnExit.Click
    'Close Program

    Me.Close()

End Sub

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPMN.Click
    'Add +1 to PMN Textbox (txtPMN)

    txtPMN.Text = (Val(txtPMN.Text) + 1).ToString()

End Sub
End Class

当我按下键盘上的特定键时,我想模拟某些按钮的点击(激活按钮代码)。例如:如果我按下“/”,我希望 Button1_Click 像我用鼠标单击按钮一样激活。然后,如果我按下我的下一个键“。”,我希望 Button2_Click 激活。

我不想使用修饰符,例如:SHIFT、CTRL、ALT

标签: vb.netkeyboard-shortcutskeypressshortcut

解决方案


请尝试这样的keychar:

Private Sub Form1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles Me.KeyPress
    If e.KeyChar = "/" Then
        Call Button1_Click(sender, New EventArgs)
    End If
end sub

使用 keydown 时,“/”键的 keycode 是 OEM,取决于键盘类型,因此 char(e.keycode) 可能不是“/”


推荐阅读