WPF无边框窗口问题:Aero Snap和最大化

13

我通过在XAML中设置以下窗口属性创建了一个无边框的WPF窗口:

... WindowStyle="None" AllowsTransparency="True" ...

这会引起一些问题:

1)已解决:它不再具有任何内置的调整大小功能

2)已解决:它不再具有任何内置的拖动功能

3)已解决:没有顶部工具栏,所以没有最小化/最大化/还原/关闭按钮

4)已解决:通过aero snap最大化或设置WindowState会防止它解除捕捉

5)通过aero snap最大化或设置WindowState将使用整个屏幕作为边界,重叠窗口工具栏。

6)通过aero snap最大化或设置WindowState似乎包含一个-7边距,使得窗口每侧多出7个像素的区域。

1-3已通过创建xaml窗口模板来解决。我使用了不可见的矩形作为处理区域,并通过重写OnApplyTemplate()应用一些代码,通过user32.dll SendMessage(...)附加功能,以实现调整大小/移动/最小化/最大化/还原/关闭。

我在这里找到了第4个问题的答案。

我尝试通过拦截WndProc中的最大化消息并手动设置大小/位置来解决5-6,但这会导致覆盖RestoreRegion的最大化大小/位置,从而无法还原窗口。

真正奇怪的是,从顶部边框调整窗口大小到屏幕顶部时,完全可以触发aero全高度捕获,没有任何问题。

所以,我已经走了很长的路,但5-6仍然是一个问题...有没有一种方法可以手动指定最大化区域?或者,有没有一种方法可以设置窗口大小而不影响restoreregion属性?


如果您能在答案中添加解决方案1-4,那就太好了。 - CularBytes
我也同意,我非常想知道第四个问题的答案。 - mgarant
“4”的解决方案,我认为这个很好。 - Ricardo Araújo
6个回答

16

最简单的完整解决方案

你好,以下解决方案以最简单的方式解决了你问题中详细描述的所有问题,并且在使用 WPF 和最新版本的 C# 语言和 .NET 框架的 Windows 10 上有效。截至 2017 年 3 月 15 日适用。如果它停止工作,请告诉我。

步骤 1:为了解决问题 1、2 和 4,在你的应用程序 XAML 的 <Window ...></Window> 标签中,在顶部或底部粘贴以下内容:

<WindowChrome.WindowChrome>
    <WindowChrome CaptionHeight="35"/>
<WindowChrome.WindowChrome>

CaptionHeight是窗口拖动区域的期望高度。

步骤 2:为了解决问题3,您需要创建标题栏和标题以及窗口控件。要做到这一点,您只需将所需的标题栏元素的每个VerticalAlignment设置为Top,或将它们放入其VerticalAlignment设置为Top的网格中(这将为所有元素执行此操作),但请确保它们的高度不能大于第1步中在XAML中声明的WindowChrome元素的CaptionHeight属性。对于所有按钮,您必须分配它们或它们的容器属性WindowChrome.IsHitTestVisibleInChrome="True"。以下是一个示例:

<Grid VerticalAlignment="Top" Background="White" Name="TitleBar" Height="35">
    <Label Content="Borderless Window Test" VerticalAlignment="Center" HorizontalAlignment="Left"/>
    <StackPanel WindowChrome.IsHitTestVisibleInChrome="True" VerticalAlignment="Center" HorizontalAlignment="Right" Orientation="Horizontal" Name="WindowControls">
        <Button Height="35" Width="35" Content="-" Padding="0" Name="MinimizeButton"/>
        <Button Height="35" Width="35" Content="+" Padding="0" Name="MaximizeButton"/>
        <Button Height="35" Width="35" Content="x" Padding="0" Name="CloseButton"/>
    </StackPanel>
</Grid>

现在,在您的代码后台的MainWindow()构造函数中,为窗口控制按钮添加适当的功能,请粘贴以下内容,调用InitializeComponent();后:


CloseButton.Click += (s, e) => Close();
MaximizeButton.Click += (s, e) => WindowState = WindowState == WindowState.Normal ? WindowState.Maximized : WindowState.Normal;
MinimizeButton.Click += (s, e) => WindowState = WindowState.Minimized;

第三步: 为了解决问题5和6,您需要钩入WmGetMinMaxInfo。要做到这一点,请转到您的代码后端,然后将来自此Pastebin的所有内容复制并粘贴到您的窗口类中。现在,在您的MainWindow()构造函数内,粘贴:

SourceInitialized += (s, e) =>
{
    IntPtr handle = (new WindowInteropHelper(this)).Handle;
    HwndSource.FromHwnd(handle).AddHook(new HwndSourceHook(WindowProc));
};

在文件菜单中通过 Project > Add References,确保引用了以下内容:

System.Management
System.Windows.Interop
System.Security.Principal
System.Runtime.InteropServices
Microsoft.Win32

检查的最佳方法是单击左上角的 Assemblies 选项卡,然后选择 Framework,接着使用窗口右上角的搜索框。现在将这些using(命名空间)全部添加到您的代码后面:

using System.Management;
using System.Windows.Interop;
using System.Security.Principal;
using System.Runtime.InteropServices;
using Microsoft.Win32;

应该都涵盖了。希望这有所帮助!


尽管我个人认为应该避免引用 Microsoft.Win32(出于可移植性等原因),但我很感激这个答案。我知道 WindowChrome,但只有你的帖子让我意识到它比我想象的要简单得多。 - Informagic
在多个分辨率设置的多监视器中并不完美,但到目前为止找到的解决方案是最好的!我特别喜欢 WindowChrome 的东西。 - Bruno
1
我已在我的电脑上进行了测试,该电脑配备了一个4K显示器和一个1080p显示器,效果非常好!谢谢 :) - Cameron Ward

5

我刚刚自己仔细研究了整个过程。由于你需要手动考虑太多内容,所以这真是一项艰巨的任务。有趣的是,我们现在对于一些简单的东西,例如基本窗口操作,已经司空见惯了。但是,查看我提供的示例代码可以很好地说明这个问题实际上涉及到了多少内容。

希望这会有所帮助,因为我自己也花了一些时间才弄明白。

MainWindow.Xaml

<Window x:Class="WpfApp1.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:WpfApp1"
    Background="Transparent"
    WindowStartupLocation="CenterScreen"
    ResizeMode="CanResizeWithGrip"
    AllowsTransparency="True"
    WindowStyle="None"
    mc:Ignorable="d"
    Title="Test Window Behavior" Height="768" Width="1024" StateChanged="Window_StateChanged" PreviewMouseLeftButtonDown="Window_PreviewMouseLeftButtonDown">

<Grid>
    <DockPanel Grid.Column="1" Grid.Row="1">
        <DockPanel x:Name="titleBar" Background="White" DockPanel.Dock="Top">
            <Rectangle Width="32" Height="32" DockPanel.Dock="Left" Fill="Red" Margin="2"/>
            <StackPanel Orientation="Horizontal" DockPanel.Dock="Right" Margin="2">

                <!-- Minimize Button -->
                <Border Width="24" Height="24" Margin="2" HorizontalAlignment="Right" MouseLeftButtonUp="OnMinimizeWindow" Grid.Column="2">
                    <Border.Style>
                        <Style TargetType="Border">
                            <Setter Property="Background" Value="Transparent" />
                            <Style.Triggers>
                                <Trigger Property="IsMouseOver" Value="True">
                                    <Setter Property="Background" Value="#FFD0D0D0" />
                                </Trigger>
                            </Style.Triggers>
                        </Style>
                    </Border.Style>
                    <TextBlock FontSize="14" HorizontalAlignment="Center" VerticalAlignment="Center" Text="0" FontFamily="Webdings" />
                </Border>

                <!-- Maximize Button -->
                <Border Width="24" Height="24" Margin="2" HorizontalAlignment="Right" MouseLeftButtonUp="OnMaximizeWindow" Grid.Column="3">
                    <Border.Style>
                        <Style TargetType="Border">
                            <Setter Property="Background" Value="Transparent" />
                            <Style.Triggers>
                                <Trigger Property="IsMouseOver" Value="True">
                                    <Setter Property="Background" Value="#FFD0D0D0" />
                                </Trigger>
                            </Style.Triggers>
                        </Style>
                    </Border.Style>
                    <TextBlock x:Name="IsMaximized" FontSize="14" HorizontalAlignment="Center" VerticalAlignment="Center" FontFamily="Webdings">
                        <TextBlock.Style>
                            <Style TargetType="TextBlock">
                                <Setter Property="Text" Value="1" />
                                <Style.Triggers>
                                    <DataTrigger Binding="{Binding Path=InternalWindowState, RelativeSource={RelativeSource FindAncestor, AncestorType=Window}}" Value="Maximized">
                                        <Setter Property="Text" Value="2" />
                                    </DataTrigger>
                                </Style.Triggers>
                            </Style>
                        </TextBlock.Style>
                    </TextBlock>
                </Border>

                <!-- Close Button -->
                <Border Width="24" Height="24" Margin="2" HorizontalAlignment="Right" MouseLeftButtonUp="OnCloseWindow" Grid.Column="4">
                    <Border.Style>
                        <Style TargetType="Border">
                            <Setter Property="Background" Value="Transparent" />
                            <Style.Triggers>
                                <Trigger Property="IsMouseOver" Value="True">
                                    <Setter Property="Background" Value="Red" />
                                </Trigger>
                            </Style.Triggers>
                        </Style>
                    </Border.Style>
                    <TextBlock FontSize="14" HorizontalAlignment="Center" VerticalAlignment="Center" Text="r" FontFamily="Webdings" />
                </Border>
            </StackPanel>

            <Label MouseLeftButtonDown="OnDragMoveWindow" MouseDoubleClick="OnMaximizeWindow" Margin="8 0 0 0" FontSize="12" VerticalContentAlignment="Center" Content="{Binding Path=Title, RelativeSource={RelativeSource FindAncestor, AncestorType=Window}, FallbackValue='Main Window'}" />
        </DockPanel>

        <Grid Background="White" DockPanel.Dock="Bottom" Height="32">
            <Label VerticalContentAlignment="Center" Content="Statusbar Text Goes Here ..." />
        </Grid>

        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="100" />
                <ColumnDefinition Width="*" />
                <ColumnDefinition Width="100" />
            </Grid.ColumnDefinitions>
            <Grid.RowDefinitions>
                <RowDefinition Height="100" />
                <RowDefinition Height="*" />
                <RowDefinition Height="100" />
            </Grid.RowDefinitions>

            <!-- Top 3 -->
            <Border Background="Gray" Grid.Row="0" Grid.Column="0" />
            <Border Background="Gray" Grid.Row="0" Grid.Column="1" BorderBrush="Black" BorderThickness="0 0 0 1" />
            <Border Background="Gray" Grid.Row="0" Grid.Column="2" />

            <!-- Middle 2 -->
            <Border Background="Gray" Grid.Row="1" Grid.Column="0" BorderBrush="Black" BorderThickness="0 0 1 0" />
            <Border Background="Gray" Grid.Row="1" Grid.Column="2" BorderBrush="Black" BorderThickness="1 0 0 0" />

            <!-- Bottom 3 -->
            <Border Background="Gray" Grid.Row="2" Grid.Column="0" />
            <Border Background="Gray" Grid.Row="2" Grid.Column="1" BorderBrush="Black" BorderThickness="0 1 0 0" />
            <Border Background="Gray" Grid.Row="2" Grid.Column="2" />
        </Grid>
    </DockPanel>
    <Grid>
        <Grid.Resources>
            <Style TargetType="Thumb">
                <Style.Setters>
                    <Setter Property="Template">
                        <Setter.Value>
                            <ControlTemplate>
                                <Border Background="Transparent" />
                            </ControlTemplate>
                        </Setter.Value>
                    </Setter>
                </Style.Setters>
            </Style>
        </Grid.Resources>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="25" />
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="25" />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="25" />
            <RowDefinition Height="*" />
            <RowDefinition Height="25" />
        </Grid.RowDefinitions>

        <!-- Top/Left -->
        <DockPanel LastChildFill="False" Grid.Row="0" Grid.Column="0">
            <Thumb DockPanel.Dock="Left" Width="4" Cursor="SizeNWSE" Tag="0" DragDelta="Thumb_DragDelta" />
            <Thumb DockPanel.Dock="Top" Height="4" Cursor="SizeNWSE" Tag="0" DragDelta="Thumb_DragDelta" />
        </DockPanel>

        <!-- Top/Right -->
        <DockPanel LastChildFill="False" Grid.Row="0" Grid.Column="2">
            <Thumb DockPanel.Dock="Right" Width="4" Cursor="SizeNESW" Tag="0" DragDelta="Thumb_DragDelta" />
            <Thumb DockPanel.Dock="Top" Height="4" Cursor="SizeNESW" Tag="0" DragDelta="Thumb_DragDelta" />
        </DockPanel>

        <!-- Bottom/Left -->
        <DockPanel LastChildFill="False" Grid.Row="2" Grid.Column="0">
            <Thumb DockPanel.Dock="Left" Width="4" Cursor="SizeNESW" Tag="1" DragDelta="Thumb_DragDelta" />
            <Thumb DockPanel.Dock="Bottom" Height="4" Cursor="SizeNESW" Tag="1" DragDelta="Thumb_DragDelta" />
        </DockPanel>

        <!-- Bottom/Right -->
        <DockPanel LastChildFill="False" Grid.Row="2" Grid.Column="2">
            <Thumb DockPanel.Dock="Right" Width="4" Cursor="SizeNWSE" Tag="1" DragDelta="Thumb_DragDelta" />
            <Thumb DockPanel.Dock="Bottom" Height="4" Cursor="SizeNWSE" Tag="1" DragDelta="Thumb_DragDelta" />
        </DockPanel>

        <!-- Left -->
        <Thumb Grid.Row="1" Grid.Column="0" Width="4" Cursor="SizeWE" Tag="0" HorizontalAlignment="Left" DragDelta="Thumb_DragDelta" />

        <!-- Top -->
        <Thumb Grid.Row="0" Grid.Column="1" Height="4" Cursor="SizeNS" Tag="0" VerticalAlignment="Top" DragDelta="Thumb_DragDelta" />

        <!-- Right -->
        <Thumb Grid.Row="1" Grid.Column="2" Width="4" Cursor="SizeWE" Tag="1" HorizontalAlignment="Right" DragDelta="Thumb_DragDelta" />

        <!-- Bottom -->
        <Thumb Grid.Row="2" Grid.Column="1" Height="4" Cursor="SizeNS" Tag="1" VerticalAlignment="Bottom" DragDelta="Thumb_DragDelta" />
    </Grid>
</Grid>

MainWindow.xaml.cs

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApp1
{
    public partial class MainWindow : Window
    {
        #region --- Declarations ---
        private Rect _location { get; set; }
        #endregion

        #region --- Constructors ---
        public MainWindow()
        {
            InitializeComponent();
        }
        #endregion

        #region --- Properties ---
        private Rect DesktopArea
        {
            get
            {
                var c = System.Windows.Forms.Cursor.Position;
                var s = System.Windows.Forms.Screen.FromPoint(c);
                var a = s.WorkingArea;
                return new Rect(a.Left, a.Top, a.Width, a.Height);
            }
        }
        #endregion

        #region --- Dependency Properties ---
        public static readonly DependencyProperty InternalWindowStateProperty = DependencyProperty.Register("InternalWindowState", typeof(WindowState), typeof(MainWindow), new PropertyMetadata(WindowState.Normal, new PropertyChangedCallback(OnInternalWindowStateChanged)));

        public WindowState InternalWindowState
        {
            get { return (WindowState)GetValue(InternalWindowStateProperty); }
            set { SetValue(InternalWindowStateProperty, value); }
        }

        private static void OnInternalWindowStateChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            MainWindow instance = (MainWindow)d;
            instance.SetInternalWindowState((WindowState)e.NewValue);
        }
        #endregion

        #region --- Private Methods ---
        private void StoreLocation()
        {
            _location = new Rect(this.Left, this.Top, this.Width, this.Height);
        }

        private void RestoreLocation()
        {
            this.Width = _location.Width;
            this.Height = _location.Height;
            this.Top = _location.Top >= 0 ? _location.Top : 0;
            this.Left = _location.Left;
        }

        private void SetMaximizedState()
        {
            this.Width = DesktopArea.Width;
            this.Height = DesktopArea.Height;
            this.Top = DesktopArea.Top;
            this.Left = DesktopArea.Left;
        }

        private void SetInternalWindowState(WindowState state)
        {
            InternalWindowState = state;

            switch (InternalWindowState)
            {
                case WindowState.Normal:
                    this.WindowState = WindowState.Normal;
                    RestoreLocation();
                    break;
                case WindowState.Maximized:
                    this.WindowState = WindowState.Normal;
                    SetMaximizedState();
                    break;
                case WindowState.Minimized:
                    this.WindowState = WindowState.Minimized;
                    break;
            }
        }
        #endregion

        #region --- Sizing Routines --- 
        private void Thumb_DragDelta(object sender, System.Windows.Controls.Primitives.DragDeltaEventArgs e)
        {
            Thumb thumb = (Thumb)sender;
            int tag = Convert.ToInt32(thumb.Tag);
            if (thumb.Cursor == Cursors.SizeWE) HandleSizeWE(tag, e);
            if (thumb.Cursor == Cursors.SizeNS) HandleSizeNS(tag, e);
            if (thumb.Cursor == Cursors.SizeNESW) HandleSizeNESW(tag, e);
            if (thumb.Cursor == Cursors.SizeNWSE) HandleSizeNWSE(tag, e);
        }

        private void HandleSizeNWSE(int tag, DragDeltaEventArgs e)
        {
            if (tag == 0)
            {
                this.Top += e.VerticalChange;
                this.Height -= e.VerticalChange;
                this.Left += e.HorizontalChange;
                this.Width -= e.HorizontalChange;
            }
            else
            {
                this.Width += e.HorizontalChange;
                this.Height += e.VerticalChange;
            }
        }

        private void HandleSizeNESW(int tag, DragDeltaEventArgs e)
        {
            if (tag == 0)
            {
                this.Top += e.VerticalChange;
                this.Height -= e.VerticalChange;
                this.Width += e.HorizontalChange;
            }
            else
            {
                this.Left += e.HorizontalChange;
                this.Width -= e.HorizontalChange;
                this.Height += e.VerticalChange;
            }
        }

        private void HandleSizeNS(int tag, DragDeltaEventArgs e)
        {
            if (tag == 0)
            {
                this.Top += e.VerticalChange;
                this.Height -= e.VerticalChange;
            }
            else
                this.Height += e.VerticalChange;
        }

        private void HandleSizeWE(int tag, DragDeltaEventArgs e)
        {
            if (tag == 0)
            {
                this.Left += e.HorizontalChange;
                this.Width -= e.HorizontalChange;
            }
            else
                this.Width += e.HorizontalChange;
        }
        #endregion

        #region --- Event Handlers ---
        private void OnDragMoveWindow(Object sender, MouseButtonEventArgs e)
        {
            if (this.InternalWindowState == WindowState.Maximized)
            {
                var c = System.Windows.Forms.Cursor.Position;
                this.InternalWindowState = WindowState.Normal;
                this.Height = _location.Height;
                this.Width = _location.Width;
                this.Top = c.Y - (titleBar.ActualHeight / 2);
                this.Left = c.X - (_location.Width / 2);
            }
            this.DragMove();
        }

        private void OnMaximizeWindow(Object sender, MouseButtonEventArgs e)
        {
            if (this.InternalWindowState == WindowState.Maximized)
                this.InternalWindowState = WindowState.Normal;
            else
                this.InternalWindowState = WindowState.Maximized;
        }

        private void OnMinimizeWindow(Object sender, MouseButtonEventArgs e)
        {
            this.InternalWindowState = WindowState.Minimized;
        }

        private void OnCloseWindow(Object sender, MouseButtonEventArgs e)
        {
            Application.Current.Shutdown();
        }

        private void Window_StateChanged(object sender, EventArgs e)
        {
            if (this.WindowState == WindowState.Maximized)
            {
                this.InternalWindowState = WindowState.Maximized;
            }
        }

        private void Window_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (this.InternalWindowState != WindowState.Maximized)
                StoreLocation();
        }
        #endregion
    }
}

出色的工作,对我来说很好用。-- 当我双击标题栏时,会出现一个小错误,窗口会最大化并还原到其正常大小。我试图修复它,但失败了。(我正在使用 Windows 10 和 2 个屏幕监视器(显示器)) - D.Kastier
非常好,因为很容易实现。我只需要安装一些引用,例如 https://dev59.com/ymw15IYBdhLWcg3wZq1r。 - EPurpl3

3

对于第5点,使用以下内容:

public WindowName() // Constructor for your window
{
this.MaxHeight = SystemParameters.WorkArea.Height;
this.MaxWidth = SystemParameters.WorkArea.Width;
}

这将确保窗口在最大化时不会重叠到任务栏。


3
只有符合以下两个条件才能使此方法生效:(a)你只有一台显示器,(b)任务栏位于你的显示器底部。其他任何配置都将导致失败。 - Jeff B

2
您可以通过处理WM_GETMINMAXINFO Win32消息来指定最大化区域。代码here展示了如何实现。这将解决问题#5和#6。
请注意,有一些我会做出不同的事情,例如在WindowProc中返回IntPtr.Zero而不是(System.IntPtr)0,并使MONITOR_DEFAULTTONEAREST成为常量。但这只是编码风格的改变,不影响最终结果。
另外,请确保关注更新,其中WindowProcSourceInitialized事件期间被钩住,而不是在OnApplyTemplate期间。那是更好的地方。如果您正在实现从Window派生的类,则另一种选择是重写OnSourceInitialized以钩住WindowProc,而不是附加到事件上。那是我通常做的事情。

1

我现在没有时间,但是我有机会的时候会查看源代码。谢谢你的回复。 - Chronicide

0

我知道这是晚回复了,但我几年前也遇到过这些问题,尤其是 #6。

就 #6 而言,如果您的 ResizeState 设置为 CanResize 或 CanResizeWithGrip,则全屏模式下的 CanMinimize 和 NoResize 会导致没有超扫描。我已经创建了自己的标题栏,具备最小化、最大化、关闭和 DragMove(带有取消捕捉支持)功能,并创建了一个拇指作为调整大小的手柄来允许调整大小。

这仍然有一些缺点,比如只能从右下角调整大小并且必须处理 #5。我还没有找到优雅的解决方案。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接