public string GetCurrentDpiConfiguration() { StringBuilder stringBuilder = new StringBuilder(); var awareness = PerMonitorDPIHelper.GetPerMonitorDPIAware(); var systemDpi = PerMonitorDPIHelper.GetSystemDPI(); switch (awareness) { case PROCESS_DPI_AWARENESS.PROCESS_DPI_UNAWARE: stringBuilder.AppendFormat("Application is DPI Unaware. Using {0} DPI.", systemDpi); break; case PROCESS_DPI_AWARENESS.PROCESS_SYSTEM_DPI_AWARE: stringBuilder.AppendFormat("Application is System DPI Aware. Using System DPI: {0}.", systemDpi); break; case PROCESS_DPI_AWARENESS.PROCESS_PER_MONITOR_DPI_AWARE: stringBuilder.AppendFormat("Application is Per-Monitor DPI Aware. Using \tmonitor DPI = {0} \t(System DPI = {1}).", m_currentDPI, systemDpi); break; } return(stringBuilder.ToString()); }
public PerMonitorDPIWindow() { Loaded += OnLoaded; if (PerMonitorDPIHelper.SetPerMonitorDPIAware()) { m_perMonitorEnabled = true; } else { throw new Exception("Enabling Per-monitor DPI Failed. Do you have [assembly: DisableDpiAwareness] in your assembly manifest [AssemblyInfo.cs]?"); } }
protected 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. if (m_perMonitorEnabled) { m_source = (HwndSource)PresentationSource.FromVisual(this); m_source.AddHook(this.HandleMessages); //Calculate the DPI used by WPF; this is same as the system DPI. m_wpfDPI = 96.0 * m_source.CompositionTarget.TransformToDevice.M11; //Get the Current DPI of the monitor of the window. m_currentDPI = PerMonitorDPIHelper.GetDpiForWindow(m_source.Handle); //Calculate the scale factor used to modify window size, graphics and text m_scaleFactor = m_currentDPI / m_wpfDPI; //Update Width and Height based on the on the current DPI of the monitor Width = Width * m_scaleFactor; Height = Height * m_scaleFactor; //Update graphics and text based on the current DPI of the monitor UpdateLayoutTransform(m_scaleFactor); } }