WPF Window 标题栏

WPF Window Titlebar

我看过这篇关于在 winforms 中获取“暗模式”标题栏的文章

很明显,您可以获得这样的 window 句柄(在 WPF 中),而不是使用 this.Handle

IntPtr hWnd = new WindowInteropHelper(GetWindow(this)).EnsureHandle();

如此有效

但我想知道我是否可以用任何颜色来做这个..

Windows 10 和 11 有一个设置可以在设置中打开任何标题栏颜色,但我想知道我是否可以获取 hWnd 并在每个应用程序中自己执行此操作,因为我可以将它变成黑色,为什么不是其他颜色?

你可以采取三种方法来解决这个问题...

1:难点,你要做的是修改Windows控制的non-client区域。

缺点是这只能通过 Windows' 内核方法实现,而且您使用的是 .NET,而不是 C/C++。但是,我们可以使用 P/Invoke。事实上,整个 Windows 表单 UI 和控制台应用程序 I/O 方法都是作为包装器提供的,可以在后台进行系统调用。因此,如 MSDN 中所述,完全可以使用 P/Invoke 访问设置非客户区所需的那些方法。

如前所述,这是一个“比目前需要的更难”的解决方案。


2:比较简单的,用XAML

制作自己的标题栏

幸运的是,从 .NET 4.5 开始,您可以使用 WindowChrome class 根据您的需要稍微调整 non-client 区域,您可以设置 WindowStyle到 none 并可以向您的应用程序添加自定义标题栏,该标题栏可以具有您喜欢的任何颜色,并且可以看起来像 Windows 或其他 OS'

中的标题栏

要开始 WindowChrome,您可以阅读以下文章 WindowChrome Class and Experiments with WindowChrome

您的代码的基础就在 <Window [...]>

下方
<WindowChrome.WindowChrome>
        <WindowChrome 
        CaptionHeight="0"
        ResizeBorderThickness="5" />
    </WindowChrome.WindowChrome>

并确保添加 WindowStyle="None" 以删除标题栏及其组件


3:最简单的一个,使用third-party库。

您还可以为 WPF 使用 third-party 组件系统,例如 MahApps.Metro。据我所知,您应该可以自定义标题栏颜色。

最终结果可能如下所示:

人们一直想看看我是如何让它工作的

把这个放在你的下面 class

[DllImport("DwmApi")] 
private static extern int DwmSetWindowAttribute(IntPtr hwnd, int attr, int[] attrValue, int attrSize);
const int DWWMA_CAPTION_COLOR = 35;


在任何函数中(主要?)

像这样获取 window 句柄或 hwnd

IntPtr hWnd = new WindowInteropHelper(this).EnsureHandle();

然后定义颜色

int[] colorstr = new int[]{0xFF00FF};

0x 字符串的格式如下 0xRRGGBB 将字母替换为相应的值

然后实现它

DwmSetWindowAttribute(hWnd, DWWMA_CAPTION_COLOR, colorstr, 4);

注意:这仅适用于 windows11


如果你懒惰,这里是完整版本

class MainWindow : Window
{

     [DllImport("DwmApi")] 
     private static extern int DwmSetWindowAttribute(IntPtr hwnd, int attr, int[] attrValue, int attrSize);
     const int DWWMA_CAPTION_COLOR = 35;

     public MainWindow()
     {
          IntPtr hWnd = new WindowInteropHelper(this).EnsureHandle();
          int[] colorstr = new int[]{0xFF00FF};
          DwmSetWindowAttribute(hWnd, DWWMA_CAPTION_COLOR, colorstr, 4);
     }

}

哦,是的,导入这些

using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;

编辑:颜色采用 BGR 格式,因此请确保它是蓝色、绿色、红色而不是红色、绿色蓝色