C# console get current screen DPI from user32.dll and gdi32.dll

using System.Runtime.InteropServices;

namespace ConsoleApp24
{
    internal class Program
    { 
        [DllImport("user32.dll")]
        static extern bool SetProcessDPIAware();
        [DllImport("user32.dll")]
        static extern IntPtr GetDC(IntPtr hwnd);

        [DllImport("user32.dll")]
        static extern int ReleaseDC(IntPtr hwnd, IntPtr hdc);

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

        const int LOGPIXELSX = 88;
        const int LOGPIXELSY = 90;
        static void Main(string[] args)
        {
            SetProcessDPIAware(); 
            GetScreenDPI();
        } 

        static void GetScreenDPI()
        {
            IntPtr hdc = GetDC(IntPtr.Zero);
            int dpiX = GetDeviceCaps(hdc, LOGPIXELSX);
            int dpiY = GetDeviceCaps(hdc, LOGPIXELSY);
            ReleaseDC(IntPtr.Zero, hdc);
            Console.WriteLine($"DPI X:{dpiX}");
            Console.WriteLine($"DPI Y:{dpiY}");
        }
    }
}

 

 

 

 

 

image

 

posted @ 2025-10-12 16:55  FredGrit  阅读(7)  评论(0)    收藏  举报