WPF get actual DPI both in x and y via PresentationSource.FromVisual TransformToDevice Matrix

//xaml
<Window x:Class="WpfApp8.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        WindowStyle="None"
        WindowState="Maximized"
        xmlns:local="clr-namespace:WpfApp8"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Window.Background>
        <ImageBrush ImageSource="C:\Users\fred\Pictures\Pics\12.jpg"/>
    </Window.Background>
    <Grid>
        
    </Grid>
</Window>



//cs
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApp8
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            var vm = new MainVM(this);
            this.DataContext=vm;
        }
    }

    public class MainVM : INotifyPropertyChanged
    {
        Window win;
        public MainVM(Window winValue)
        {
            win=winValue;
            if(win!=null)
            {
                win.Loaded+=Win_Loaded;
            }
        }

        private void Win_Loaded(object sender, RoutedEventArgs e)
        {
            var actualDpi = GetDpi(win);
            MessageBox.Show($"ActualDPIX:{actualDpi.DpiX},ActualDPIY:{actualDpi.DpiY}");
        }

        public static (double DpiX, double DpiY) GetDpi(Visual visual)
        {
            var source = PresentationSource.FromVisual(visual);
            if (source?.CompositionTarget != null)
            {
                Matrix matrix = source.CompositionTarget.TransformToDevice;
                //MessageBox.Show($"XScaleFactor:{matrix.M11},YScaleFactor:{matrix.M22}");
                return (96.0 * matrix.M11, 96.0 * matrix.M22); // DPI = 96 * scale factor
            }

            return (96.0, 96.0); // default DPI
        }

        public event PropertyChangedEventHandler? PropertyChanged;
        private void OnPropertyChanged([CallerMemberName]string propertyName="")
        {
            var handler = PropertyChanged;
            if(handler!=null)
            {
                handler?.Invoke(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}

 

 

 

 

posted @ 2025-07-18 19:47  FredGrit  阅读(7)  评论(0)    收藏  举报