标签:rgs 句柄 像素 ssi post parameter screen 初始 ima
在设置桌面不同分辨率以及较大DPI下,窗口如何显示的问题。(此例中仅设置高度)
前端:
1 <Window x:Class="WindowHeightChangedForDpi.MainWindow" 2 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 3 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 4 xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 5 xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 6 xmlns:local="clr-namespace:WindowHeightChangedForDpi" 7 mc:Ignorable="d" 8 Title="MainWindow" SizeToContent="WidthAndHeight" WindowStartupLocation="CenterScreen"> 9 <Viewbox x:Name="RootViewbox" Stretch="None"> 10 <Grid x:Name="RootGrid" Width="1000" MaxHeight="680" MinHeight="520" ClipToBounds="True"> 11 12 </Grid> 13 </Viewbox> 14 </Window>
后台:
1 public partial class MainWindow : Window 2 { 3 public MainWindow() 4 { 5 InitializeComponent(); 6 Loaded += InitWindowActualHeight_OnLoaded; 7 } 8 9 #region 设置窗口对屏幕高度的自适应 10 11 private void InitWindowActualHeight_OnLoaded(object sender, RoutedEventArgs e) 12 { 13 Loaded -= InitWindowActualHeight_OnLoaded; 14 InitWindowActualHeight(); 15 } 16 17 private const double WindowShadowHeight = 0; 18 19 private void InitWindowActualHeight() 20 { 21 //获取任务栏高度 22 var taskbarHeight = SystemParameters.PrimaryScreenHeight - SystemParameters.WorkArea.Height; 23 //获取窗体所在屏幕的高度 24 var height = GetScreenHeight(); 25 var visibleAreaHeight = height - taskbarHeight; 26 27 //可显示高度 > 窗口最大高度 28 if (visibleAreaHeight > RootGrid.MaxHeight + WindowShadowHeight) 29 { 30 //设置高度等于最大高度 31 RootGrid.Height = RootGrid.MaxHeight; 32 } 33 //可显示高度 < 窗口最小高度 34 else if (visibleAreaHeight < RootGrid.MinHeight + WindowShadowHeight) 35 { 36 //设置Viewbox高度=可视高度-阴影高度(此处通过绽放显示窗口,所以不能通过设置窗口或者设置内容的高度来实现) 37 RootViewbox.Height = visibleAreaHeight - WindowShadowHeight; 38 //等比例缩小 39 RootViewbox.Stretch = Stretch.Uniform; 40 } 41 else 42 { 43 //设置高度等于最小高度 44 RootGrid.Height = RootGrid.MinHeight; 45 } 46 } 47 const double DpiPercent = 96; 48 private double GetScreenHeight() 49 { 50 var intPtr = new WindowInteropHelper(this).Handle;//获取当前窗口的句柄 51 var screen = Screen.FromHandle(intPtr);//获取当前屏幕 52 53 double height = 0; 54 using (Graphics currentGraphics = Graphics.FromHwnd(intPtr)) 55 { 56 double dpiXRatio = currentGraphics.DpiX / DpiPercent; 57 double dpiYRatio = currentGraphics.DpiY / DpiPercent; 58 height = screen.Bounds.Height / dpiYRatio; 59 //var width = screen.Bounds.Width / dpiXRatio; 60 //var left = screen.Bounds.Left / dpiXRatio; 61 //var top = screen.Bounds.Top / dpiYRatio; 62 } 63 return height; 64 } 65 #endregion
注:获取的屏幕高度为屏幕像素,需要转换为WPF单位。
标签:rgs 句柄 像素 ssi post parameter screen 初始 ima
原文地址:https://www.cnblogs.com/kybs0/p/9834023.html