What is the best way to simulate a Click with MouseUp & MouseDown events or otherwise?

前端 未结 5 719
天涯浪人
天涯浪人 2020-11-30 02:17

In WPF most controls have MouseUp and MouseDown events (and the mouse-button-specific variations) but not a simple Click event that ca

5条回答
  •  再見小時候
    2020-11-30 02:21

    First add a Mouse event click function:

    /// 
    /// Returns mouse click.
    /// 
    /// mouseeEvent
    public static MouseButtonEventArgs MouseClickEvent()
    {
        MouseDevice md = InputManager.Current.PrimaryMouseDevice;
        MouseButtonEventArgs mouseEvent = new MouseButtonEventArgs(md, 0, MouseButton.Left);
        return mouseEvent;
    }
    

    Add a click event to one of your WPF controls:

    private void btnDoSomeThing_Click(object sender, RoutedEventArgs e)
    {
        // Do something
    }
    

    Finally, Call the click event from any function:

    btnDoSomeThing_Click(new object(), MouseClickEvent());
    

    To simulate double clicking, add a double click event like PreviewMouseDoubleClick and make sure any code starts in a separate function:

    private void lvFiles_PreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)
    {
        DoMouseDoubleClick(e);
    }
    
    private void DoMouseDoubleClick(RoutedEventArgs e)
    {
        // Add your logic here
    }
    

    To invoke the double click event, just call it from another function (like KeyDown):

    private void someControl_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
    {
        if (e.Key == Key.Enter)
            DoMouseDoubleClick(e);
    }
    

提交回复
热议问题