4

I used UserControl for my application and i need to put shortcut key for my application i placed this code but not working.Anyone suggestion plz

My XAML Code

<Button  Name="ucBtnUpload" ToolTip="Upload F2" Cursor="Hand" Click="ucBtnUpload_Click" KeyUp="ucBtnUpload_KeyUp_1" >

My Code Behind

private void ucBtnUpload_KeyUp_1(object sender, KeyEventArgs e)
{
if (e.Key == Key.F2)
            {

                Test opj = new Test();
                opj.ShowDialog();

             }
}
RKT
  • 81
  • 1
  • 9
  • Does your handler get fired? Have you wired up the event in the XAML, correctly? `` – Geoff James Jun 21 '16 at 10:23
  • 2
    Are you sure that you want a Key-Event on a button? This requires that the button is Focused... – lokusking Jun 21 '16 at 10:27
  • 3
    Usually you do this via InputBindings and commands in WPF, not by intercepting key events and handling them. – Joey Jun 21 '16 at 10:30
  • Yes works fine mine too when i use sample application but i use it to my project nothing will happen. Thats why i mention i use it User control for my application – RKT Jun 21 '16 at 10:35
  • Does this answer your question? [Keyboard shortcuts in WPF](https://stackoverflow.com/questions/1361350/keyboard-shortcuts-in-wpf) – StayOnTarget Jul 21 '20 at 13:14

2 Answers2

5

You need to try something similar to this

private void AddHotKeys()
{
        try
        {
            RoutedCommand firstSettings = new RoutedCommand();
            firstSettings.InputGestures.Add(new KeyGesture(Key.A, ModifierKeys.Alt));
            CommandBindings.Add(new CommandBinding(firstSettings , My_first_event_handler));

            RoutedCommand secondSettings = new RoutedCommand();
            secondSettings.InputGestures.Add(new KeyGesture(Key.B, ModifierKeys.Alt));
            CommandBindings.Add(new CommandBinding(secondSettings , My_second_event_handler));
        }
        catch (Exception err)
        {
            //handle exception error
        }
}

Events

private void My_first_event_handler(object sender, ExecutedRoutedEventArgs e) 
{
      //handler code goes here.
      MessageBox.Show("Alt+A key pressed");
}

private void My_second_event_handler(object sender, RoutedEventArgs e) 
{
     //handler code goes here. 
     MessageBox.Show("Alt+B key pressed");
}

If you are following MVVM you could try this reference

<UserControl.InputBindings>
<KeyBinding Modifiers="Control" 
            Key="E" 
            Command="{input:CommandBinding EditCommand}"/>

See the reference
msdn adding key bindings

Community
  • 1
  • 1
Eldho
  • 7,795
  • 5
  • 40
  • 77
0

You should be able to do this in your xaml

<Window.InputBindings>
    <KeyBinding Command="{Binding MyCommand}" Key="F2"/>
</Window.InputBindings>

<Button Command="{Binding MyCommand}"/>

MyCommand is an ICommand implemented in your windows' / view's viewmodel.

So both the button and the F2 inputbinding will execute the same command.

Janne Matikainen
  • 5,061
  • 15
  • 21