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單位,屏幕高寬/位置


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM