vb.net 如何设置Button的快捷键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39947538/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 20:05:28  来源:igfitidea点击:

How to set up shortcut key for Button

vb.netaccess-keys

提问by gpanev

Can anyone help me understand how to set a shortcut key in the following code? It should be Alt+X (Exit is the name of the button). I tried cmd_Exit.text="&Exit", but it printed the "&" and shortcut key was not set up.

谁能帮我理解如何在下面的代码中设置快捷键?它应该是 Alt+X(退出是按钮的名称)。我试过了cmd_Exit.text="&Exit",但它打印了“&”并且没有设置快捷键。

Private Sub cmdExit_Click(sender As Object, e As EventArgs) Handles cmdExit.Click
    'cmdExit.Capture()
    Dim response = MsgBox("Are you sure you want to exit?", CType(MsgBoxStyle.YesNo + MsgBoxStyle.Exclamation, MsgBoxStyle), "Leaving?")
    If response = MsgBoxResult.Yes Then     'if yes exit the application
        Application.Exit()
    End If
End Sub

回答by soohoonigan

You can check that Alt+X is being pressed with the keydown event, and then call your exit sub with it:

您可以使用 keydown 事件检查 Alt+X 是否被按下,然后用它调用您的退出子:

Note, you will need KeyPreview set to True in your main form

请注意,您需要在主表单中将 KeyPreview 设置为 True

Private Sub Form1_KeyDown(sender As Object, e As KeyEventArgs) Handles Me.KeyDown
    If e.KeyCode = Keys.X AndAlso e.Modifiers = Keys.Alt Then
        e.Handled = True
        cmdExit_Click(sender, e) 'or cmdExit.PerformClick()
    End If
End Sub

回答by EYADISMAIL

set Form KeyPreview = True

(Event) Form1_KeyDown

(事件) Form1_KeyDown

If (e.KeyCode = Keys.F1) Then
    MessageBox.Show("TEST", Button1.Text)
End If

回答by ERSDF

Private Sub Form1_KeyDown(sender As Object, e As KeyEventArgs) Handles Me.KeyDown

    If e.KeyCode = Keys.X AndAlso e.Modifiers = Keys.Alt Then
        e.Handled = True
        cmdExit_Click(sender, e) 'or cmdExit.PerformClick()
    End If
End Sub