C# WPF - DragMove window and Click Event

I am building a borderless application. What i need to achieve is to move the window by simply click and drag on an image it contains but i also want to do something when clicked.

this is how my app looks Just a button, i have functionality for left and right clicks but can't figure how to implement drag now. This is what my code looks like

private void btnHome_MouseDown(object sender, MouseButtonEventArgs e)
    {
        if(e.LeftButton == MouseButtonState.Released)
        {
            toggle();
        }
        else if(e.LeftButton == MouseButtonState.Pressed)
        {
            DragMove();
        }
    }

Right now only drag works, If i rearrange their occurrence then only left click would work. Right click functionality is working as expected right now.

2 answers

  • answered 2017-11-12 19:58 Yitzchak

    EDIT: Well I found the problem! You listen to MouseDownEvent!!!!

    Just link the new event to the following new function =]

    private void btnHome_MouseUp(object sender, MouseButtonEventArgs e)
    {
         toggle();
    }
    
    private void btnHome_MouseDown(object sender, MouseButtonEventArgs e)
    {
        DragMove();
        RaiseEvent(new MouseButtonEventArgs(e.MouseDevice, e.Timestamp, MouseButton.Left) 
        { 
            RoutedEvent = MouseLeftButtonUpEvent 
        });
    }
    

  • answered 2017-11-13 16:21 mm8

    Do your thing once the DragMove() method has returned, i.e. when the mouse capture has been released:

    private void btnHome_MouseDown(object sender, MouseButtonEventArgs e)
    {
        if (e.LeftButton == MouseButtonState.Pressed)
        {
            DragMove();
            System.Diagnostics.Debug.Write("some action...");
        }
    }
    

    Or, if you want to do something before the mouse is captured, you could use a boolean flag:

    private bool _capture;
    private void btnHome_MouseDown(object sender, MouseButtonEventArgs e)
    {
        if (e.LeftButton == MouseButtonState.Pressed)
        {
            if (_capture)
            {
                DragMove();
                _capture = false;
            }
            else
            {
                System.Diagnostics.Debug.Write("some action...");
    
                _capture = true;
                btnHome.RaiseEvent(new MouseButtonEventArgs(e.MouseDevice, e.Timestamp, MouseButton.Left)
                {
                    RoutedEvent = MouseDownEvent
                });
            }
        }
    }