Skip to content

Commit

Permalink
Constrain CenterOwner window to screen. (AvaloniaUI#14982)
Browse files Browse the repository at this point in the history
* Constrain CenterOwner window to screen.

This logic is also present in WPF: https://github.com/dotnet/wpf/blob/3880169c020787b7e3383acb3679e5e4d538c602/src/Microsoft.DotNet.Wpf/src/PresentationFramework/System/Windows/Window.cs#L3707-L3711

Fixes AvaloniaUI#2578

* Ensure min <= max when constraining window pos.
  • Loading branch information
grokys authored Mar 15, 2024
1 parent 1249a5f commit 5d4dd93
Showing 1 changed file with 15 additions and 1 deletion.
16 changes: 15 additions & 1 deletion src/Avalonia.Controls/Window.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
using Avalonia.Platform;
using Avalonia.Reactive;
using Avalonia.Styling;
using Avalonia.Utilities;

namespace Avalonia.Controls
{
Expand Down Expand Up @@ -943,7 +944,20 @@ private void SetWindowStartupLocation(Window? owner = null)
var ownerRect = new PixelRect(
owner.Position,
PixelSize.FromSize(ownerSize, scaling));
Position = ownerRect.CenterRect(rect).Position;
var childRect = ownerRect.CenterRect(rect);

if (Screens.ScreenFromWindow(this)?.WorkingArea is { } constraint)
{
var maxX = constraint.Right - rect.Width;
var maxY = constraint.Bottom - rect.Height;

if (constraint.X <= maxX)
childRect = childRect.WithX(MathUtilities.Clamp(childRect.X, constraint.X, maxX));
if (constraint.Y <= maxY)
childRect = childRect.WithY(MathUtilities.Clamp(childRect.Y, constraint.Y, maxY));
}

Position = childRect.Position;
}
}

Expand Down

0 comments on commit 5d4dd93

Please sign in to comment.