C# 獲取當前屏幕的寬高和位置

上一篇博客《C# 獲取當前屏幕DPI》,介紹瞭如何獲取當前屏幕的DPI設置html

本章主要介紹如何獲取當前窗口所在屏幕的信息編程

當前屏幕信息

若是當前是單屏幕,能夠直接獲取主屏幕post

    var primaryScreen = Screen.PrimaryScreen;

若是當前是多屏,建議經過窗口句柄獲取Screen信息url

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

獲取屏幕高寬/位置

DpiPercent

DPI轉換比例常量,DpiPercent = 96;spa

爲什麼DpiPercent爲96 ?有一個概念「設備無關單位尺寸」,其大小爲1/96英寸。好比:code

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

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

關於WPF單位和系統DPI,能夠參考《WPF編程寶典》中相關章節get

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

相關文章
相關標籤/搜索