C# 获取真实DPI(分辨率)


环境: window10

   框架:4.5.2

由于 windows10的DPI设置 无法直接获取屏幕的真实长宽
获取长宽代码
int iH = Screen.PrimaryScreen.Bounds.Height;
int iW = Screen.PrimaryScreen.Bounds.Width;

两种方法:
1、使用上边代码获取缩放后的长宽
iH*DPI(1.25)=真实高度
DPI获取方法:

        #region Dll引用
        [DllImport("User32.dll", EntryPoint = "GetDC")]
        private extern static IntPtr GetDC(IntPtr hWnd);

        [DllImport("User32.dll", EntryPoint = "ReleaseDC")]
        private extern static int ReleaseDC(IntPtr hWnd, IntPtr hDC);

        [DllImport("gdi32.dll")]
        public static extern int GetDeviceCaps(IntPtr hdc, int nIndex);

        [DllImport("User32.dll")]
        public static extern int GetSystemMetrics(int hWnd);

        const int DESKTOPVERTRES = 117;
        const int DESKTOPHORZRES = 118;
        
        const int SM_CXSCREEN = 0;
        const int SM_CYSCREEN = 1;

        #endregion


        /// 
        /// 获取DPI缩放比例
        /// 
        /// 
        /// 
        public static void GetDPIScale(ref float dpiscalex, ref float dpiscaley)
        {
            int x = GetSystemMetrics(SM_CXSCREEN);
            int y = GetSystemMetrics(SM_CYSCREEN);
            IntPtr hdc = GetDC(IntPtr.Zero);
            int w = GetDeviceCaps(hdc, DESKTOPHORZRES);
            int h = GetDeviceCaps(hdc, DESKTOPVERTRES);
            ReleaseDC(IntPtr.Zero, hdc);
            dpiscalex = (float)w / x;
            dpiscaley = (float)h / y;
        }

2、直接获取分辨率

            /// 
            /// 获取分辨率
            /// 
            /// 
            /// 
            private static void GetResolving(ref int width, ref int height)
            {
                IntPtr hdc = GetDC(IntPtr.Zero);
                width = GetDeviceCaps(hdc, DESKTOPHORZRES);
                height = GetDeviceCaps(hdc, DESKTOPVERTRES);
                ReleaseDC(IntPtr.Zero, hdc);
            }

以上完成了。

后边会出个全屏录制demo