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


        /// <summary>
        /// 獲取DPI縮放比例
        /// </summary>
        /// <param name="dpiscalex"></param>
        /// <param name="dpiscaley"></param>
        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;
        }
View Code

2、直接獲取分辨率

            /// <summary>
            /// 獲取分辨率
            /// </summary>
            /// <param name="width"></param>
            /// <param name="height"></param>
            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);
            }
View Code

以上完成了。

后邊會出個全屏錄制demo 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM