C#获取屏幕分辨率

发布于:2025-06-25 ⋅ 阅读:(17) ⋅ 点赞:(0)

方法一:借助 System.Windows.Forms(适用于 Windows 窗体应用程序)

using System;
using System.Windows.Forms;

class ScreenResolution
{
    static void Main()
    {
        // 获取主屏幕的分辨率
        int width = Screen.PrimaryScreen.Bounds.Width;
        int height = Screen.PrimaryScreen.Bounds.Height;
        
        Console.WriteLine($"主屏幕分辨率: {width} x {height}");
        
        // 获取所有屏幕的信息(适用于多显示器环境)
        foreach (Screen screen in Screen.AllScreens)
        {
            Console.WriteLine($"屏幕: {screen.DeviceName}");
            Console.WriteLine($"  分辨率: {screen.Bounds.Width} x {screen.Bounds.Height}");
            Console.WriteLine($"  工作区域: {screen.WorkingArea.Width} x {screen.WorkingArea.Height}");
            Console.WriteLine($"  是否为主屏幕: {screen.Primary}");
        }
    }
}

方法二:使用 System.Drawing(需要添加引用)

using System;
using System.Drawing;

class ScreenResolution
{
    static void Main()
    {
        // 获取当前屏幕的分辨率(与方法一类似)
        int width = SystemInformation.PrimaryMonitorSize.Width;
        int height = SystemInformation.PrimaryMonitorSize.Height;
        
        Console.WriteLine($"屏幕分辨率: {width} x {height}");
    }
}

方法三:采用 WPF(Windows Presentation Foundation)方式

using System;
using System.Windows;

class ScreenResolution
{
    static void Main()
    {
        // 在WPF应用程序中获取屏幕分辨率
        double width = SystemParameters.PrimaryScreenWidth;
        double height = SystemParameters.PrimaryScreenHeight;
        
        Console.WriteLine($"屏幕分辨率: {width} x {height}");
    }
}

方法四:通过 P/Invoke 调用 Win32 API

using System;
using System.Runtime.InteropServices;

class ScreenResolution
{
    [DllImport("user32.dll")]
    static extern int GetSystemMetrics(int nIndex);
    
    private const int SM_CXSCREEN = 0; // 屏幕宽度
    private const int SM_CYSCREEN = 1; // 屏幕高度
    
    static void Main()
    {
        int width = GetSystemMetrics(SM_CXSCREEN);
        int height = GetSystemMetrics(SM_CYSCREEN);
        
        Console.WriteLine($"屏幕分辨率: {width} x {height}");
    }
}

各方法适用场景

**方法一和方法二:**适用于 Windows 窗体应用程序,能够获取主屏幕或者所有屏幕的分辨率。
**方法三:**适用于 WPF 应用程序,返回的是与设备无关的单位。
**方法四:**适合需要直接调用底层 Windows API 的情况。

多显示器环境注意事项

若你的系统连接了多个显示器,可以通过以下方式获取相关信息:
// 获取所有屏幕
Screen[] screens = Screen.AllScreens;
Console.WriteLine($"检测到 {screens.Length} 个显示器");

// 获取特定屏幕的分辨率(例如第二个屏幕)
if (screens.Length > 1)
{
    Rectangle bounds = screens[1].Bounds;
    Console.WriteLine($"第二个屏幕分辨率: {bounds.Width} x {bounds.Height}");
}

网站公告

今日签到

点亮在社区的每一天
去签到