Mohammad Sheriyar Sid
Mohammad Sheriyar Sid

Reputation: 35

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.

Upvotes: 0

Views: 2849

Answers (2)

mm8
mm8

Reputation: 169160

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
            });
        }
    }
}

Upvotes: 1

Yitzchak
Yitzchak

Reputation: 3416

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 
    });
}

Upvotes: 0

Related Questions