zoukankan      html  css  js  c++  java
  • C# 获取当前屏幕的宽高和位置

    上一篇博客《C# 获取当前屏幕DPI》,介绍了如何获取当前屏幕的DPI设置

    本章主要介绍如何获取当前窗口所在屏幕的信息

    当前屏幕信息

    如果当前是单屏幕,可以直接获取主屏幕

        var primaryScreen = Screen.PrimaryScreen;

    如果当前是多屏,建议通过窗口句柄获取Screen信息

        var window = Window.GetWindow(ExportButton);//获取当前主窗口
        var intPtr = new WindowInteropHelper(window).Handle;//获取当前窗口的句柄
        var screen = Screen.FromHandle(intPtr);//获取当前屏幕

    获取屏幕高宽/位置

    DpiPercent

    DPI转换比例常量,DpiPercent = 96;

    为何DpiPercent为96 ?有一个概念“设备无关单位尺寸”,其大小为1/96英寸。比如:

    【物理单位尺寸】=1/96英寸 * 96dpi = 1像素;

    【物理单位尺寸】=1/96英寸 * 120dpi = 1.25像素;

    关于WPF单位和系统DPI,可以参考《WPF编程宝典》中相关章节

    Screen.Bounds

    Bounds对应的是屏幕的分辨率,而要通过Bounds.Width获取屏幕的宽度,则需要将其转化为WPF单位的高宽。

    步骤:

    1. 获取当前屏幕的物理尺寸(X/Y方向的像素)--如X方向 currentGraphics.DpiX / DpiPercent
    2. 将Screen.Bounds的信息转化为WPF单位信息 --如高度 screen.Bounds.Width / dpiXRatio
        using (Graphics currentGraphics = Graphics.FromHwnd(intPtr))
        {
            double dpiXRatio = currentGraphics.DpiX / DpiPercent;
            double dpiYRatio = currentGraphics.DpiY / DpiPercent;
            var width = screen.Bounds.Width / dpiXRatio;
            var height = screen.Bounds.Height / dpiYRatio;
            var left = screen.Bounds.Left / dpiXRatio;
            var top = screen.Bounds.Top / dpiYRatio;
        }

      

    直接获取屏幕的高宽

    也可以通过System.Windows.SystemParameters,直接获取主屏幕信息,不过这个类只能获取主屏幕的高宽

    这里的高宽指的是实际高宽。

    主屏幕:

        var screenHeight = SystemParameters.PrimaryScreenHeight;
        var screenWidth = SystemParameters.PrimaryScreenWidth;

    多屏时全屏幕:

        var primaryScreenHeight = SystemParameters.FullPrimaryScreenHeight;
        var primaryScreenWidth = SystemParameters.FullPrimaryScreenWidth;

    当前工作区域:(除去任务栏的区域)

        var workAreaWidth = SystemParameters.WorkArea.Size.Width;
        var workAreaHeight = SystemParameters.WorkArea.Size.Height;

    关键字:WPF单位,屏幕高宽/位置

  • 相关阅读:
    【Oracle 12c】最新CUUG OCP-071考试题库(58题)
    【Oracle 12c】最新CUUG OCP-071考试题库(57题)
    【Oracle 12c】最新CUUG OCP-071考试题库(56题)
    【Oracle 12c】最新CUUG OCP-071考试题库(55题)
    voip,
    处理xmpp 离线信息,
    流程,xmpp发送信息,
    折腾我几天的 消息状态,
    三者的区别,
    bundle,
  • 原文地址:https://www.cnblogs.com/kybs0/p/9122526.html
Copyright © 2011-2022 走看看