Windows 10 上的 WinForms 深色标题栏 [英] WinForms Dark title bar on Windows 10

查看:28
本文介绍了Windows 10 上的 WinForms 深色标题栏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 WinForms 应用程序,它会自动适应 Windows 10 上的深色/浅色主题.我的问题是我的窗口的标题栏始终保持白色,无论用户选择哪个主题.

I have a WinForms application which automatically adjusts to the dark/light theme on Windows 10. My problem is that the title bar of my window always stays white, regardless which theme the user selects.


顶部是最新的,底部是我想要的(用 Photoshop 模拟)

例如参见 explorer.这不是 UWP 应用,但它在 Windows 1903 和更高版本上使用深色标题栏(选择深色主题时).

See explorer for example. That is not an UWP app, however it uses a dark title bar on Windows 1903 and newer (when a dark theme is selected).

我怎样才能达到同样的目的?我不想使用任何自定义标题栏,因为我希望应用程序的外观和行为也像旧版 Windows 上的任何本机应用程序一样.

How can I achieve the same thing? I do not want to use any custom titlebar as I want the application to look and behave like any native application on older Windows versions as well.

推荐答案

所以经过长时间的搜索,我终于找到了这个问题的答案.诀窍是使用dwmapi.dllDwmSetWindowAttribute 并将未记录的常量DWMWA_USE_IMMERSIVE_DARK_MODE 传递到函数中.在 C# 中,这个代码看起来有点像这样(适用于 WinForms 和 WPF):

So after some long searching, I have finally found the answer for this. The trick is to use dwmapi.dll's DwmSetWindowAttribute and passing the undocumented constant DWMWA_USE_IMMERSIVE_DARK_MODE into the function. In C#, the code for this looks a little something like this (works with both WinForms and WPF):

/*
using System.Runtime.InteropServices;
*/

[DllImport("dwmapi.dll")]
private static extern int DwmSetWindowAttribute(IntPtr hwnd, int attr, ref int attrValue, int attrSize);

private const int DWMWA_USE_IMMERSIVE_DARK_MODE_BEFORE_20H1 = 19;
private const int DWMWA_USE_IMMERSIVE_DARK_MODE = 20;

private static bool UseImmersiveDarkMode(IntPtr handle, bool enabled)
{
    if (IsWindows10OrGreater(17763))
    {
        var attribute = DWMWA_USE_IMMERSIVE_DARK_MODE_BEFORE_20H1;
        if (IsWindows10OrGreater(18985))
        {
            attribute = DWMWA_USE_IMMERSIVE_DARK_MODE;
        }

        int useImmersiveDarkMode = enabled ? 1 : 0;
        return DwmSetWindowAttribute(handle, (int)attribute, ref useImmersiveDarkMode, sizeof(int)) == 0;
    }

    return false;
}

private static bool IsWindows10OrGreater(int build = -1)
{
    return Environment.OSVersion.Version.Major >= 10 && Environment.OSVersion.Version.Build >= build;
}

这篇关于Windows 10 上的 WinForms 深色标题栏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆