1

My question is simple. Is it possible to trigger mouseup and mousedown on keyup and keydown event respectivey in WPF.

I have set of event handlers for mouse down and mouse up in my custom control. I want to trigger the same if the user try to press the spacebar on my custom button.

    private void CustomButton_MouseDown(object sender, MouseButtonEventArgs e)
    {
        eventlabel.Content = "Mousedown event Triggered";            
    }

    private void CustomButton_MouseUp(object sender, MouseButtonEventArgs e)
    {
        eventlabel.Content = "MouseUp event Triggered";
    }

    private void CustomButton_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Space)
        {
            //Need to trigger all the handlers of mousedown
        }
    }

    private void CustomButton_KeyUp(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Space)
        {
            //Need to trigger all the handlers of mouseup
        }
    }
Gopichandar
  • 2,742
  • 2
  • 24
  • 54
  • what error you get after trying out – Tharif May 28 '15 at 08:45
  • Sounds like [XY problem](http://meta.stackexchange.com/q/66377), are you trying to achieve something like [this](http://stackoverflow.com/q/8272681/1997232) ? – Sinatr May 28 '15 at 08:50
  • Do you need to simulate mouse events or just execute the code in the event handler? If latter, just move it to the separate method and call it. – Sriram Sakthivel May 28 '15 at 08:51
  • No. I have set of event handlers for mouse down and mouse up. I want to trigger the same if the user press the spacebar on my custom button. – Gopichandar May 28 '15 at 08:59

2 Answers2

2

You can raise Events in all UIElements with RaiseEvent(EventArgs). The MouseButtonArgsEventsArgs can be used as followed in the KeyDown-EventHandler:

  MouseDevice mouseDevice = Mouse.PrimaryDevice;
  MouseButtonEventArgs mouseButtonEventArgs = new MouseButtonEventArgs(mouseDevice, 0, MouseButton.Left); 
  mouseButtonEventArgs.RoutedEvent = Mouse.MouseDownEvent;
  mouseButtonEventArgs.Source = this;
  RaiseEvent(mouseButtonEventArgs);

(modified example from https://social.msdn.microsoft.com/Forums/vstudio/de-DE/7ec6b75b-b808-48ca-a880-fafa9025da6e/how-to-raise-a-click-event-on-an-uielement?forum=wpf)

0

Answer mentioned by Tobias works for me. But, it need some tweak.

elementName.RaiseEvent(new MouseButtonEventArgs(Mouse.PrimaryDevice, 0, MouseButton.Left)
{
  RoutedEvent = Mouse.MouseDownEvent,
  Source = this,
});

Here is the Reference

Community
  • 1
  • 1
Gopichandar
  • 2,742
  • 2
  • 24
  • 54