Firing MouseLeftButtonDown event programmatically

爱⌒轻易说出口 提交于 2020-01-03 08:29:14

问题


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:


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 ) ).




回答2:


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.




回答3:


var grid = new Grid();            

int timestamp = new TimeSpan(DateTime.Now.Ticks).Milliseconds;
const MouseButton mouseButton = MouseButton.Left;
var mouseDownEvent =
   new MouseButtonEventArgs(Mouse.PrimaryDevice, timestamp, mouseButton) {
       RoutedEvent = UIElement.MouseLeftButtonDownEvent,
       Source = grid,
   };

This is how I fire the event in my test code.



来源:https://stackoverflow.com/questions/3033839/firing-mouseleftbuttondown-event-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!