c# WPF 程序窗口根据电脑屏幕的不同尺寸自动切换大小 主窗口显示问题

首先介绍MainWindow.xaml

<Window x:Class="Sys.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:Sys"
        xmlns:loc="clr-namespace:Sys.WinForm"
        xmlns:sys="clr-namespace:System;assembly=mscorlib"
        xmlns:myLocal="clr-namespace:Sys.Util"
        xmlns:myLocalCommon="clr-namespace:Sys.Common"
        xmlns:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"
        mc:Ignorable="d"
        PreviewKeyDown="WinMain_PreviewKeyDown"
        PreviewKeyUp="WinMain_PreviewKeyUp"
        Style="{StaticResource CustomWindowStyle}"
        Name ="WinMain"  Height="768" Width="1024"  WindowStartupLocation="CenterScreen" Closing="WinMain_Closing">
    <Window.Resources>

其中是FrameworkElement 类的一些属性配置,Height和Width就是窗口的高和宽,WindowStartupLocation可设置窗口初始化时的位置。还可用Maxheight和Minheight来设置最大和最小值。

SizeToContent="WidthAndHeight" 窗体的尺寸将随内容而变化,这个可以保证窗口内的控件都能展示出来。

而想要让窗口根据不同的电脑大小展示不同大小的窗口则需要获得屏幕的大小

double x = SystemParameters.WorkArea.Width;//得到屏幕工作区域宽度
double y = SystemParameters.WorkArea.Height;//得到屏幕工作区域高度
double x1= SystemParameters.PrimaryScreenWidth;//得到屏幕整体宽度
double y1 = SystemParameters.PrimaryScreenHeight;//得到屏幕整体高度

直接在MainWindow.xaml.cs 中的 private MainWindow()

加入

 double width = SystemParameters.PrimaryScreenWidth;
 double height = SystemParameters.PrimaryScreenHeight;
 this.Width = width * (0.7);
 this.Height = height * (0.7);

0.7就表示的是高或宽的70%

发现一个问题,当子窗口下开启一个窗口再关闭后,会导致主窗口自动最小化。目前解决方式:

在子窗口.closed(); 后加入

MainWindow.GetInstance().Activate();

Activate();是让主窗口处于激活状态,从而避免了进入最小化。

发布了16 篇原创文章 · 获赞 10 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/Hilaph/article/details/101776628