C# 怎么判断屏幕是第几屏幕?屏幕是垂直还是水平?屏幕的分辨率?

一、怎么判断屏幕是第几屏幕?

可以使用System.Windows.Forms.Screen.AllScreens属性来获取所有已连接的屏幕,并根据鼠标位置或窗口的位置来判断它所在的屏幕索引。

cs 复制代码
using System;
using System.Windows.Forms;

// 获取鼠标当前位置所在的屏幕
Point cursorPos = Cursor.Position;
Screen currentScreen = Screen.FromPoint(cursorPos);
int screenIndex = Array.IndexOf(Screen.AllScreens, currentScreen);

Console.WriteLine($"当前屏幕是第 {screenIndex + 1} 个屏幕。");

二、屏幕是垂直还是水平?

对于Windows桌面应用程序而言,屏幕的方向通常是指其分辨率的比例,而不是物理旋转。系统并不直接提供API来检测屏幕是否被物理旋转,但可以通过比较屏幕的宽度和高度来间接判断分辨率是否接近于横屏或竖屏模式。

cs 复制代码
Screen currentScreen = Screen.PrimaryScreen; // 或者使用上面的方法获取到的当前屏幕
bool isLandscape = currentScreen.Bounds.Width > currentScreen.Bounds.Height;
if (isLandscape)
{
    Console.WriteLine("当前屏幕为横向(水平)模式");
}
else
{
    Console.WriteLine("当前屏幕为纵向(垂直)模式");
}

三、屏幕的分辨率?

在C#中获取屏幕分辨率,可以使用System.Windows.Forms.Screen类的方法来获取主屏幕或其他特定屏幕的分辨率信息。

以下是如何获取主屏幕分辨率的示例:

cs 复制代码
using System;
using System.Windows.Forms;

class Program
{
    static void Main()
    {
        // 获取主屏幕分辨率
        Screen primaryScreen = Screen.PrimaryScreen;
        
        int screenWidth = primaryScreen.Bounds.Width;
        int screenHeight = primaryScreen.Bounds.Height;

        Console.WriteLine($"主屏幕分辨率:{screenWidth} * {screenHeight}");
    }
}

如果想获取所有连接屏幕的分辨率,可以遍历Screen.AllScreens数组:

cs 复制代码
foreach (Screen screen in Screen.AllScreens)
{
    int index = Array.IndexOf(Screen.AllScreens, screen) + 1;
    string screenOrientation = screen.Bounds.Width > screen.Bounds.Height ? "横向" : "纵向";
    
    Console.WriteLine($"第 {index} 屏幕分辨率:{screen.Bounds.Width} * {screen.Bounds.Height},方向:{screenOrientation}");
}

这样不仅可以得到每个屏幕的分辨率,还能判断出屏幕大致是垂直(纵向)还是水平(横向)显示。不过需要注意的是,这里的"方向"基于分辨率比例而非物理旋转角度。

如果需要检测设备物理旋转状态,请查阅对应平台的具体API支持。

相关推荐
用户37215742613515 小时前
C# 提取 PDF 附件:包括文档附件和页面注释附件
c#
寂寞的船15 小时前
【Unity Bug挑战】第12期 Awaitable 二次 await 死锁之谜 —— 为什么同一个异步操作等两次就卡死?
unity·c#·游戏引擎·bug
huaqianzkh2 天前
WinForm C#:循环修改控件UI闪烁卡顿?SuspendLayout / ResumeLayout 与 BeginUpdate 优化
开发语言·ui·c#
用户3721574261353 天前
C# 实现 Excel 单元格保护:锁定公式并允许编辑指定区域
c#·ai编程·编程语言
公子小六3 天前
基于.NET的Windows窗体编程之WinForms数据持久化(1)
windows·microsoft·c#·.net·winforms
三雷科技3 天前
第6章第4节:自定义分词器
开发语言·c#
zhanghaha13143 天前
C# 系列教程_12 字符串 string 保姆级系统教程(面向新手,大量示例 + 原理讲解)
开发语言·数据库·c#
Coder_Shenshen4 天前
罗克韦尔ACD工程归档离线变量树解析
算法·c#
寂寞的船4 天前
【Unity知识速递】第10期 Unity GC 零分配实战:从 UnityEngine.Pool 到手动 GC 控制的全链路优化
jvm·unity·c#·游戏引擎·lucene
1-1=04 天前
C# 数据结构和特殊类型
数据结构·c#·.net·.netcore