Пример #1
0
        /// <summary>
        /// <see cref="FrameworkElement.Loaded"/> event handler.
        /// </summary>
        /// <param name="sender">event sender.</param>
        /// <param name="args">event arguments.</param>
        protected virtual void OnLoaded(object sender, RoutedEventArgs args)
        {
            // WPF has already scaled window size, graphics and text based on system DPI. In order to scale the window based on monitor DPI, update the
            // window size, graphics and text based on monitor DPI. For example consider an application with size 600 x 400 in device independent pixels
            //		- Size in device independent pixels = 600 x 400
            //		- Size calculated by WPF based on system/WPF DPI = 192 (scale factor = 2)
            //		- Expected size based on monitor DPI = 144 (scale factor = 1.5)

            // Similarly the graphics and text are updated updated by applying appropriate scale transform to the top level node of the WPF application

            // Important Note: This method overwrites the size of the window and the scale transform of the root node of the WPF Window. Hence,
            // this sample may not work "as is" if
            //	- The size of the window impacts other portions of the application like this WPF  Window being hosted inside another application.
            //  - The WPF application that is extending this class is setting some other transform on the root visual; the sample may
            //     overwrite some other transform that is being applied by the WPF application itself.

            SystemDpi = DpiHelper.GetSystemDpi();
            var source = (HwndSource)PresentationSource.FromVisual(this);

            source?.AddHook(WindowProcedureHook);

            // Calculate the DPI used by WPF.
            var transform = source?.CompositionTarget?.TransformToDevice;

            WpfDpi = new DPI(96 * (transform?.M11 ?? 1), 96 * (transform?.M22 ?? 1));

            if (IsPerMonitorEnabled && (source != null))
            {
                // Get the Current DPI of the monitor of the window.
                CurrentDpi = DpiHelper.GetDpiForHwnd(source.Handle);

                // Calculate the scale factor used to modify window size, graphics and text.
                ScaleFactor = new DPI(CurrentDpi.X / WpfDpi.X, CurrentDpi.Y / WpfDpi.Y);
            }

            UpdateWindowSize();
            UpdateLocation();

            // Update graphics and text based on the current DPI of the monitor.
            UpdateLayoutTransform(ScaleFactor);
            OnDpiChanged();
        }