1

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.

Chris Dunaway
  • 10,974
  • 4
  • 36
  • 48
cody196
  • 13
  • 1
  • 4
  • WinForms or WPF? - Either way, buttons tend to have an `Alt-S` shortcut assigned and menu options have the `Ctrl-S` action. I think this is just the way Windows Apps have developed over the years – JayV May 26 '18 at 19:32

1 Answers1

2

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
JayV
  • 3,238
  • 2
  • 9
  • 14
  • Nice answer! Though please see [the difference between And and AndAlso](https://stackoverflow.com/q/8409467/3740093). – Visual Vincent May 26 '18 at 21:45
  • @VisualVincent Thanks for the tip. Normally I spend my time in C# and the `AndAlso` keyword totally slipped my mind. I edited to use `AndAlso` – JayV May 26 '18 at 21:56
  • @cody196 That good to hear. Don't forget to Accept it as the answer to help other people looking for a similar solution – JayV May 26 '18 at 22:30
  • @ visual vincent: Yeah sure! – cody196 May 28 '18 at 01:52