grijalvaromero
grijalvaromero

Reputation: 605

Drag a WPF window around the desktop with a button

I have this code for dragging my Window with its MouseDown Event.

private void Window_MouseDown(object sender, MouseButtonEventArgs e)
{
    if (e.ChangedButton == MouseButton.Left)
        this.DragMove();
}

But I want to do this using a Button, because my form is transparent. And Using the same function for that button's MouseDown event will not work.

How can I achieve this?

Upvotes: 1

Views: 743

Answers (3)

Hamid Siaban
Hamid Siaban

Reputation: 345

You have to use PreviewMouseDown instead of MouseDown event. And do not forget to mark the event "Handled" in the end.

XAML code:

<Button x:Name="Button_Move" PreviewMouseDown="Window_Main_MouseDown"/>

C# code:

private void Window_Main_MouseDown(object sender, MouseButtonEventArgs e)
{
    if (e.ChangedButton == System.Windows.Input.MouseButton.Left)
    {
        this.DragMove();
        e.Handled = true;
    }
}

Upvotes: 2

grijalvaromero
grijalvaromero

Reputation: 605

My Finally Code was here:

private Point startPoint;
private void btnChat_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            startPoint = e.GetPosition(btnChat);
        }

        private void btnChat_PreviewMouseMove(object sender, MouseEventArgs e)
        {
            var currentPoint = e.GetPosition(btnChat);
            if (e.LeftButton == MouseButtonState.Pressed &&
                btnChat.IsMouseCaptured &&
                (Math.Abs(currentPoint.X - startPoint.X) >
                    SystemParameters.MinimumHorizontalDragDistance ||
                Math.Abs(currentPoint.Y - startPoint.Y) >
                    SystemParameters.MinimumVerticalDragDistance))
            {
                // Prevent Click from firing
                btnChat.ReleaseMouseCapture();
                DragMove();
            }
        }

Upvotes: 0

ebattulga
ebattulga

Reputation: 11011

Use border instead of Button. Because DragMove only work on PrimaryMouseButton event. Not work on Click event

XAML

<Border Background="Blue" MouseLeftButtonDown="Border_MouseLeftButtonDown">
</Border>

CODE

private void Border_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
        DragMove();
}

Upvotes: 1

Related Questions