WPF下实现拖动任意地方都可以拖动窗口

首先在xaml中添加事件

<Window PreviewMouseLeftButtonDown="Window_PreviewMouseLeftButtonDown"
        PreviewMouseMove="Window_PreviewMouseMove"
        PreviewMouseLeftButtonUp="Window_PreviewMouseLeftButtonUp"/>

然后脚本输入

Point _pressedPosition;
bool _isDragMoved = false;

#region 窗口移动

private void Window_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    _pressedPosition = e.GetPosition(this);
}

private void Window_PreviewMouseMove(object sender, MouseEventArgs e)
{
    if (Mouse.LeftButton == MouseButtonState.Pressed && _pressedPosition != e.GetPosition(this))
    {
        _isDragMoved = true;
        DragMove();
    }
}

private void Window_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
    if (_isDragMoved)
    {
        _isDragMoved = false;
        e.Handled = true;
    }
}

#endregion

效果图:
WPF下实现拖动任意地方都可以拖动窗口_第1张图片

参考文章:https://blog.csdn.net/u013113678/article/details/121071628

你可能感兴趣的:(WPF,C#,wpf)