如何添加" ctrl +" vb.net中按钮的快捷方式。例如,当按下ctrl + s时,我需要执行保存按钮的单击事件。
答案 0 :(得分:1)
Winforms解决方案
在Form类中,将其KeyPreview
属性设置为true,在Form构造函数中设置它的示例,在此处设置或通过Designer设置:
Public Sub New()
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
Me.KeyPreview = True
End Sub
然后您需要做的就是处理Form的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}" />
在你的Code Behind(.xaml.vb)中,你的函数调用保存例程,例如:
Private Sub SaveAction(sender As Object, e As RoutedEventArgs)
Debug.Print("Call Save action here")
End Sub