如何在 vb.net 中为按钮提供"ctrl + "快捷键



如何在 vb.net 中添加" Ctrl + "快捷方式到按钮。例如,当按下ctrl + s时,我需要执行保存按钮的单击事件。

Winforms Solution

在 Form 类中,将其KeyPreview属性设置为 true,例如在 Form 构造函数中设置它,可以在此处设置它,也可以通过设计器设置它:

Public Sub New()
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
Me.KeyPreview = True
End Sub

然后,您需要做的就是处理表单的KeyDown事件,如下所示:

Private Sub Form1_KeyDown(sender As Object, e As KeyEventArgs) Handles MyBase.KeyDown
If (e.Control AndAlso e.KeyCode = Keys.S) Then
Debug.Print("Call Save action here")
End If
End Sub

WPF 解决方案(不使用 MVVM 模式(

将此添加到您的 .xaml 文件

<Window.Resources>
<RoutedUICommand x:Key="SaveCommand" Text="Save" />
</Window.Resources>
<Window.CommandBindings>
<CommandBinding Command="{StaticResource SaveCommand}" Executed="SaveAction" />
</Window.CommandBindings>
<Window.InputBindings>
<KeyBinding Key="S" Modifiers="Ctrl" Command="{StaticResource SaveCommand}" />
</Window.InputBindings>

更改按钮定义以包含Command="{StaticResource SaveCommand}",例如:

<Button x:Name="Button1" Content="Save" Command="{StaticResource SaveCommand}" />

在代码隐藏 (.xaml.vb( 中,将函数用于调用保存例程,例如:

Private Sub SaveAction(sender As Object, e As RoutedEventArgs)
Debug.Print("Call Save action here")
End Sub

最新更新