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支持。

相关推荐
小羊没烦恼!3 天前
初探性能优化——2个月到4小时的性能提升
java·开发语言·windows·算法·c#
神仙别闹3 天前
基于C#+MySQL实现(WinForm)个人聊天室软件
c#
kybs19913 天前
全球灾害数据分析可视化 毕业设计-附源码66794
vue.js·spring boot·mysql·安全·django·c#·asp.net
Polevne3 天前
C# SFTP客户端实现文件传输
c#·ssh
samble3 天前
从零搭建灌装监控系统(四):深色主题与样式系统,ResourceDictionary 统一管理
c#·wpf·mvvm·样式·工业控制
cjp5603 天前
024 . WPF MVVM类封装优化
c#
淡海水4 天前
13-04-面试-源码级深度追问链
数据结构·unity·面试·c#·游戏引擎·源码·il2cpp
asdzx674 天前
如何使用 C# 提取 PPT 文本与图片
c#·ppt·提取文本
2501_930707784 天前
使用C#代码使用条件格式为 Excel 隔行设置颜色
c#·excel
何以解忧唯有撸码4 天前
【开源】c#造个轮子-日程安排工具
c#·自定义控件