views:

61

answers:

2

Hi,

I'm trying to manually fire a MouseLeftButtonDown event on a WPF control programmatically, as I am using the Microsoft Surface SDK, which does not fire MouseLeftButtonDown events, but ContactDown events. Basically I'm trying to push the MouseLeftButtonDown event down to the control, to fire off the correct behavior on the control, while handling a ContactDown event.

I'm guessing I have to somehow use the RaiseEvent method on the control to do this with MouseButtonEventArgs, but I'm having some trouble figuring out the parameters.

Thanks in advance for your help!

+1  A: 

The wish to trigger a certain event in a control is quite often an indicator of a design problem in the code. Event handlers should trigger behavior, not perform it. I would suggest that you move the code that performs the action triggered by the MouseLeftButtonDown event handler into a separate method. Then the same method can be called from the ContactDown event handler.

Fredrik Mörk
I agree that would be the best solution, but as I do not have access to the source code of this particular control (only the binary), I'm afraid that won't work.
RajenK
A: 

You can spoof mouse and key events using Win32 interop. Investigate the SendInput function on MSDN/pinvoke.net.

Note that this will cause the system and other applications to think the mouse was actually clicked. If you just want to initiate a WPF event, try RaiseEvent( new RoutedEventArgs( UIElement.MouseLeftButtonDownEvent ) ).

chaiguy
Thanks for the tip. I'm getting an exception with that RaiseEvent method you posted: Object of type 'System.Windows.RoutedEventArgs' cannot be converted to type 'System.Windows.Input.MouseButtonEventArgs'.
RajenK
Try `RaiseEvent( new MouseButtonEventArgs( Mouse.PrimaryDevice, Environment.TickCount, MouseButton.Left ) );`
chaiguy
InvalidOperationException occurs with that one:Every RoutedEventArgs must have a non-null RoutedEvent associated with it.
RajenK
Ok this works: `startOpBtn.RaiseEvent( new MouseButtonEventArgs( Mouse.PrimaryDevice, Environment.TickCount, MouseButton.Left ) { RoutedEvent = Button.ClickEvent } );` however, it uses the click event. `UIElement.MouseLeftButtonDown` and `UIElement.MouseLeftButtonUp` compile and run, but they won't "click" the button, probably because the mouse cursor needs to actually be over the button to make the hit-testing work.
chaiguy
Thanks chaiguy, I guess I'll look for an alternative solution.
RajenK