Flicker on DragMove of Border-less WPF Custom Window
-
04-04-2022 - |
Question
I have a custom, border-less window intended to act as a base form for future WPF projects. I've managed to simulate near all of the native window behaviours, but I'm having a problem with DragMove. I wanted the window to reposition itself above the task bar when the user drags the its title bar behind the windows task bar, so that the whole window is visible. I managed to do this by overriding the OnLocationChanged method, because all the mouse related handlers are blocked during DragMove.
This works like a charm, except I get a flicker when dragging the title bar along the windows task bar. I can see it is trying to redraw the window where it would have been, down below, and then it immediately redraws the window again in the intended place.
How can I interrupt this redrawing properly? Many Thanks!
This, this, this and this SO question did not help me at all, unfortunately. Here is an extract of my code:
protected override void OnLocationChanged(EventArgs e)
{
base.OnLocationChanged(e);
var activeScreenHeight = System.Windows.Forms.Screen.FromHandle(new WindowInteropHelper(this).Handle).WorkingArea.Bottom - ToolbarSnapThreshold;
if (activeScreenHeight < this.RestoreBounds.Top)
{
this.Top = activeScreenHeight - this.RestoreBounds.Height + ToolbarSnapThreshold;
}
}
protected void MaximizeOrRestore()
{
this.WindowState = (this.WindowState == WindowState.Normal) ? WindowState.Maximized : WindowState.Normal;
this.lastNonMinimizedState = this.WindowState;
}
protected void RestoreAndDragMove(MouseButtonState leftMouseButtonState)
{
if (leftMouseButtonState == MouseButtonState.Pressed)
{
if (this.WindowState == WindowState.Maximized)
{
var activeScreenWidth = System.Windows.Forms.Screen.FromHandle(new WindowInteropHelper(this).Handle).Bounds.Width;
var windowCurrentWidth = this.RestoreBounds.Width;
var windowPositionAdjustX = this.relativeMousePositionX - (windowCurrentWidth / 2);
if (windowPositionAdjustX < 0)
{
windowPositionAdjustX = 0;
}
else if (windowPositionAdjustX + windowCurrentWidth > activeScreenWidth)
{
windowPositionAdjustX = activeScreenWidth - windowCurrentWidth;
}
this.WindowState = WindowState.Normal;
this.lastNonMinimizedState = this.WindowState;
this.Left = windowPositionAdjustX - this.relativeMousePositionX + this.originalMousePositionX;
this.Top = 0 - this.relativeMousePositionY + this.originalMousePositionY;
}
this.DragMove();
}
}
private void Window_TitleBarClicked(object sender, MouseButtonEventArgs e)
{
if (e.LeftButton == MouseButtonState.Pressed)
{
this.relativeMousePositionX = e.GetPosition(this).X;
this.relativeMousePositionY = e.GetPosition(this).Y;
this.originalMousePositionX = System.Windows.Forms.Cursor.Position.X;
this.originalMousePositionY = System.Windows.Forms.Cursor.Position.Y;
if (e.ClickCount == 2)
{
this.MaximizeOrRestore();
}
}
}
No correct solution