コード例 #1
0
ファイル: DpiHandler.cs プロジェクト: galri/Dapplo.Windows
        /// <summary>
        ///     Retrieve the DPI value for the supplied window handle
        /// </summary>
        /// <param name="hWnd">IntPtr</param>
        /// <returns>dpi value</returns>
        public static int GetDpi(IntPtr hWnd)
        {
            // Use the easiest method, but this only works for Windows 10
            if (WindowsVersion.IsWindows10OrLater)
            {
                return(GetDpiForWindow(hWnd));
            }

            // Use the second easiest method, but this only works for Windows 8.1 or later
            if (WindowsVersion.IsWindows81OrLater)
            {
                var  hMonitor = User32Api.MonitorFromWindow(hWnd, MonitorFrom.DefaultToNearest);
                uint dpiX;
                uint dpiY;
                if (GetDpiForMonitor(hMonitor, MonitorDpiType.EffectiveDpi, out dpiX, out dpiY))
                {
                    return((int)dpiX);
                }
            }

            // Fallback to the global DPI settings
            using (var hdc = SafeDeviceContextHandle.FromHWnd(hWnd))
            {
                return(Gdi32Api.GetDeviceCaps(hdc, DeviceCaps.LOGPIXELSX));
            }
        }
コード例 #2
0
        /// <summary>
        ///     Retrieve the DPI value for the supplied window handle
        /// </summary>
        /// <param name="hWnd">IntPtr</param>
        /// <returns>dpi value</returns>
        public static uint GetDpi(IntPtr hWnd)
        {
            if (!User32Api.IsWindow(hWnd))
            {
                return(DpiHandler.DefaultScreenDpi);
            }

            // Use the easiest method, but this only works for Windows 10
            if (WindowsVersion.IsWindows10OrLater)
            {
                return(GetDpiForWindow(hWnd));
            }

            // Use the second easiest method, but this only works for Windows 8.1 or later
            if (WindowsVersion.IsWindows81OrLater)
            {
                var hMonitor = User32Api.MonitorFromWindow(hWnd, MonitorFrom.DefaultToNearest);
                // ReSharper disable once UnusedVariable
                if (GetDpiForMonitor(hMonitor, MonitorDpiType.EffectiveDpi, out var dpiX, out var dpiY))
                {
                    return(dpiX);
                }
            }

            // Fallback to the global DPI settings
            using (var hdc = SafeWindowDcHandle.FromWindow(hWnd))
            {
                if (hdc == null)
                {
                    return(DpiHandler.DefaultScreenDpi);
                }
                return((uint)Gdi32Api.GetDeviceCaps(hdc, DeviceCaps.LOGPIXELSX));
            }
        }