问题
how to add a " ctrl + " shortcut to button in vb.net. For example I need to perform click event of save button when ctrl + s is pressed.
回答1:
Winforms Solution
In your Form class, set its KeyPreview
property to true, example of it being set in the Form constructor, either set it here or via the Designer:
Public Sub New()
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
Me.KeyPreview = True
End Sub
Then all you need to do is handle the KeyDown
event for the Form, like this:
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 Solution (Not using MVVM pattern)
Add this to your .xaml file
<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>
Alter your button definition to include Command="{StaticResource SaveCommand}"
, for example:
<Button x:Name="Button1" Content="Save" Command="{StaticResource SaveCommand}" />
In your Code Behind (.xaml.vb) put your function to call the save routine, such as:
Private Sub SaveAction(sender As Object, e As RoutedEventArgs)
Debug.Print("Call Save action here")
End Sub
来源:https://stackoverflow.com/questions/50546326/how-to-give-a-ctrl-shortcut-key-for-a-button-in-vb-net