DragMove() and Maximize

Igor Ostancov picture Igor Ostancov · Jul 28, 2012 · Viewed 8.4k times · Source

I have a problem with my custom window (AllowTransparency, WindowStyle=None) in WPF. DragMove() method works good, but when I maximize window, or it maximizing automatically by Windows 7 Aero Snap, this method does not work at all. So I can't unsnap window with mouse drag and return it state to WindowState.Normal. Left and Right Aero Snap works good, I can snap and unsnap window without a problem. But when it maximized, nothing works except Win+Down combination. Maybe somebody knows how to solve this problem or where can I find other ways to do proper DragMove of custom window with working Aero Snap features?

Answer

groaner picture groaner · Jul 28, 2012

Here is my method. Try make it shorter )))

private void InitHeader()
{
    var border = Find<Border>("borderHeader");
    var restoreIfMove = false;

    border.MouseLeftButtonDown += (s, e) =>
    {
        if (e.ClickCount == 2)
        {
            if ((ResizeMode == ResizeMode.CanResize) ||
                (ResizeMode == ResizeMode.CanResizeWithGrip))
            {
                SwitchState();
            }
        }
        else
        {
            if (WindowState == WindowState.Maximized)
            {
                restoreIfMove = true;
            }

            DragMove();
        }
    };
    border.MouseLeftButtonUp += (s, e) =>
    {
        restoreIfMove = false;
    };
    border.MouseMove += (s, e) =>
    {
        if (restoreIfMove)
        {
            restoreIfMove = false;
            var mouseX = e.GetPosition(this).X;
            var width = RestoreBounds.Width;
            var x = mouseX - width / 2;

            if (x < 0)
            {
                x = 0;
            }
            else
            if (x + width > screenSize.X)
            {
                x = screenSize.X - width;
            }

            WindowState = WindowState.Normal;
            Left = x;
            Top = 0;
            DragMove();
        }
    };
}

private void SwitchState()
{
    switch (WindowState)
    {
        case WindowState.Normal:
        {
            WindowState = WindowState.Maximized;
            break;
        }
        case WindowState.Maximized:
        {
            WindowState = WindowState.Normal;
            break;
        }
    }
}

(To get screenSize I use native methods)