最简单的完整解决方案
你好,以下解决方案以最简单的方式解决了你问题中详细描述的所有问题,并且在使用 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;
应该都涵盖了。希望这有所帮助!