C#获取屏幕分辨率(大小)

本文介绍了如何使用C#获取屏幕的分辨率,并给出了一个简单的示例来计算如何使窗口在屏幕上居中显示。
            获取屏幕分辨率
            int SH = Screen.PrimaryScreen.Bounds.Height;
            int SW = Screen.PrimaryScreen.Bounds.Width;  
            获取窗口居中Top和Left
            int thisH=100;
            int thisW=200;
            int SH = (Screen.PrimaryScreen.Bounds.Height - 30 - thisH) / 2;
            int SW = (Screen.PrimaryScreen.Bounds.Width - 10 - thisW) / 2;
C# 中,可以通过多种方式获取当前屏幕的分辨率,尤其在 Windows 窗体应用程序中,开发者可以使用 .NET 提供的类库实现这一功能。以下是一些常用方法: ### 获取屏幕分辨率 可以通过 `Screen.PrimaryScreen.Bounds` 属性获取主屏幕的宽度和高度,示例代码如下: ```csharp int width = Screen.PrimaryScreen.Bounds.Width; int height = Screen.PrimaryScreen.Bounds.Height; MessageBox.Show(width.ToString() + " x " + height.ToString()); ``` 该方法适用于获取主屏幕的分辨率,并可用于调整窗体大小以适应当前屏幕[^1]。 ### 获取所有屏幕信息 在多显示器环境下,可以通过 `Screen.AllScreens` 属性获取所有屏幕的信息。例如,获取第二个屏幕的分辨率: ```csharp Screen[] screens = Screen.AllScreens; Console.WriteLine($"检测到 {screens.Length} 个显示器"); if (screens.Length > 1) { Rectangle bounds = screens[1].Bounds; Console.WriteLine($"第二个屏幕分辨率: {bounds.Width} x {bounds.Height}"); } ``` 此方法适用于需要处理多显示器环境的应用程序,能够获取每个显示器的分辨率信息[^2]。 ### 获取主显示器的尺寸 可以使用 `System.Windows.Forms.SystemInformation.PrimaryMonitorSize` 获取主显示器的尺寸,单位为像素: ```csharp int width = System.Windows.Forms.SystemInformation.PrimaryMonitorSize.Width; int height = System.Windows.Forms.SystemInformation.PrimaryMonitorSize.Height; Console.WriteLine(width + "px * " + height + "px"); ``` 该方法适用于 Windows 窗体应用程序,能够获取主显示器的分辨率[^3]。 ### 获取工作区域的尺寸 可以使用 `Screen.GetWorkingArea` 方法获取当前窗体所在屏幕的工作区域,排除任务栏等系统界面占用的空间: ```csharp System.Drawing.Rectangle area = Screen.GetWorkingArea(this); int width = area.Width; int height = area.Height; Console.WriteLine(width + "px * " + height + "px"); ``` 此方法也适用于 Windows 窗体应用程序,能够获取当前屏幕的有效工作区域[^3]。 --- ### 示例代码:获取屏幕分辨率并显示 以下是一个完整的示例,演示如何获取主屏幕的分辨率并显示在消息框中: ```csharp private void GetScreenResolution() { int width = Screen.PrimaryScreen.Bounds.Width; int height = Screen.PrimaryScreen.Bounds.Height; MessageBox.Show("当前屏幕分辨率: " + width + " x " + height); } ``` 此方法适用于窗体应用程序中动态获取屏幕分辨率,并根据分辨率调整窗体布局或位置。 --- ### 注意事项 - 在多显示器环境中,应使用 `Screen.AllScreens` 获取所有显示器的分辨率信息,以确保程序能够正确处理同屏幕的布局。 - 若需要获取工作区域而非整个屏幕的大小,应使用 `Screen.GetWorkingArea` 方法。 - 在某些情况下,如 WPF 应用程序中,分辨率单位可能与设备无关,需根据具体需求选择合适的 API。 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值