Search code examples
wpfbuttonkeyboardvirtual

wpf button click as keyboard output


I have two button name "A", and "B" want to click them equal to click keyboard A and B buttons. So any one can give me a quick way to achieve it.

Thanks


Solution

  • I'd do it the following way. First add event handler for the key down event of window or some other parent container:

    <Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" KeyDown="Window_KeyDown" Width="525"> [...]
    

    And the event handler:

    private void Window_KeyDown(object sender, KeyEventArgs e)
    {
            if (e.Key == Key.A)
                ButtonA.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
            else if (e.Key == Key.B)
                ButtonB.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
    }