public class DpiAwareWindow : Window
{
public new static readonly DependencyProperty LeftProperty =
DependencyProperty.RegisterAttached(nameof(Left), typeof(double), typeof(DpiAwareWindow),
new PropertyMetadata(OnPlacementChange));
public new double Left
{
get => (double)GetValue(LeftProperty);
set => SetValue(LeftProperty, value);
}
public new static readonly DependencyProperty TopProperty =
DependencyProperty.RegisterAttached(nameof(Top), typeof(double), typeof(DpiAwareWindow),
new PropertyMetadata(OnPlacementChange));
public new double Top
{
get => (double)GetValue(TopProperty);
set => SetValue(TopProperty, value);
}
public new static readonly DependencyProperty WidthProperty =
DependencyProperty.RegisterAttached(nameof(Width), typeof(double), typeof(DpiAwareWindow),
new PropertyMetadata(OnPlacementChange));
public new double Width
{
get => (double)GetValue(WidthProperty);
set => SetValue(WidthProperty, value);
}
public new static readonly DependencyProperty HeightProperty =
DependencyProperty.RegisterAttached(nameof(Height), typeof(double), typeof(DpiAwareWindow),
new PropertyMetadata(OnPlacementChange));
public new double Height
{
get => (double)GetValue(HeightProperty);
set => SetValue(HeightProperty, value);
}
private static void OnPlacementChange(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
if (obj is not DpiAwareWindow window) return;
IntPtr hwnd = new WindowInteropHelper(window).EnsureHandle();
if (!NativeMethods.GetWindowPlacement(hwnd, out WINDOWPLACEMENT placement))
return;
placement.normalPosition = RECT.FromXYWH((int)window.Left, (int)window.Top, (int)window.Width, (int)window.Height);
NativeMethods.SetWindowPlacement(hwnd, ref placement);
}