Reputation: 2832
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
}
}
Upvotes: 1
Views: 2110
Reputation: 2832
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
Upvotes: 0
Reputation: 41
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)
Upvotes: 2