WindowsAppSDK icon indicating copy to clipboard operation
WindowsAppSDK copied to clipboard

Discussion: Dark mode for applications

Open sylveon opened this issue 5 years ago • 91 comments

Discussion: Dark mode for applications

Currently, reliably detecting dark mode in Win32 applications requires either reading the registry or using undocumented methods from uxtheme.dll.

I strongly suggest to document those two existing methods:

  • ShouldAppsUseDarkMode:
    • This allows apps to detect whether the dark theme is used for apps.
    • Particularly useful to follow system settings, like Microsoft Edge and UWP-based apps do.
    • Changes to this can be detected by listening for WM_SETTINGCHANGE.
  • ShouldSystemUseDarkMode:
    • This allows apps to detect whether the taskbar, start menu and other system shell elements uses the dark theme or not.
    • Particularly useful for determining if a white or black notification area icon should be used. OneDrive already does this.
    • Changes to this can be detected by listening for WM_SETTINGCHANGE.

This will allow existing apps to easily implement dark theme support, and to follow system settings without relying on workarounds. A WinRT API should probably be exposed (the two settings and an event to listen for changes) as well, but some applications are already tentatively using those two APIs, so it would be the best case to document the Win32 APIs, as those won't have to do any significant work to adopt an official solution rather than an undocumented one (and, truth be told, they are much simpler to use than their WinRT counterparts, especially if your language doesn't have a WinRT projection available)

Also, there exists other APIs in uxtheme.dll which might be of interest for people transitioning to WinUI and/or XAML islands:

  • SetPreferredAppMode:
    • This allows apps to enable dark theme support for Win32 controls. This is notably used by Windows Explorer for its dark theme.
  • AllowDarkModeForWindow:
    • Once the app mode is set to AllowDark using the API above, it is a per-window opt-in.
    • Once this method is called, the Win32 controls in the window uses dark theme if the system dark theme is enabled, and automatically switches to light theme when the user changes their settings.
    • Note that some controls might need to have their theme manually set to DarkMode_Explorer for this to be effective
    • Dark mode ribbon can be opt-in with the window property UI_PKEY_DarkModeRibbon

Those methods are useful because when transitioning, it allows developers to use a dark theme for old controls and new controls alike, to get a somewhat consistent UI. Darkening Win32 or winforms controls manually is extremely hard to get right, and leveraging the work done in Windows Explorer would prevent a lot of misdirected attempts at dark theming Win32 controls.

EVEN MORE, there's an undocumented window attribute allowing dark mode title bars (DWMWA_USE_IMMERSIVE_DARK_MODE). This one was even used by the command prompt itself and openly on GitHub, before it got removed from the OSS version because it was internal (see https://github.com/microsoft/terminal/commit/bc7eb9611030aed3204aff4e662c318cbf9143a6#diff-e26a93b2aa9fea92ebf24336c4fe6412L19-L22). No true dark mode comes without a dark titlebar, and customizing the titlebar is a complex endeavour that would be greatly simplified by the publication of this attribute.

All of the APIs mentioned have been added since the introduction of dark mode Explorer, and have proven to be stable or only very slightly modified, so I'm sad they are being kept private because it would allow so many apps to get a dark mode (light mode makes me cry 😢)

sylveon avatar May 21 '20 01:05 sylveon

Thanks! Project Reunion APIs will be defined in metadata like WinRT objects are so they can be projected to all languages and all runtimes.

Can you mock up what an API for this would look like? Maybe something like:

enum WindowThemePreferenceColorMode {
    None = 0,
    Dark,
    Light
}
runtimeclass WindowThemePreference {
    static WindowThemePreferenceColorMode SystemColorMode { get; };
    static WindowThemePreferenceColorMode AppColorMode { get; };
    static event EventHandler<Object> PreferenceChanged;

    static void SetAppPreferredColorMode(WindowThemePreferenceColorMode mode);
    static void SetWindowPreferredColorMode(WindowId window, WindowThemePreferenceColorMode mode);
    static void SetWindowTitleBarPreferredColorMode(WindowId window, WindowThemePreferenceColorMode mode);
}

jonwis avatar May 21 '20 05:05 jonwis

Ideally it would remain a RequestedTheme = Light/Dark value in the App.xaml or Window Xaml element. The Window Frame and TitleBar reflecting that setting, or if it is not set, the System setting.

mdtauk avatar May 21 '20 05:05 mdtauk

My suggestion is for non-XAML code, so RequestedTheme is not a thing. Currently, this code has no reliable way to detect the theme, and I would very much like to be able to follow user preferences for non-XAML parts of my app that is using XAML Islands (eg. tray icon and its context menu).

I can't adopt WinUI's UWP app model "clone" intended for desktop apps either without a significant rewrite. C++/WinRT is already causing compilation time and error headaches even when only a small part of my code is using it, so I would actually rather not adopt it at all (not to mention that IDL is a complete PITA).

If a WinRT API for this only supports WinUI desktop app scenarios, it would be useless to me, and I'll just use the undocumented functions I listed above.

I would suggest documenting the OS APIs that I listed (and already exist as well as being usable in uxtheme.dll today, they are just not documented and exported by ordinal only) in some Windows SDK update, because it would reach a wider audience (all Win32 devs) than exposing this through only a WinRT API would (only early adopters of Project Reunion, and people whose language of choice includes a WinRT projection)

For example, a Delphi-based Win32 app (you know those still exist) or a C++ app using an older version of the C++ compiler (like VS2013) could use ShouldAppsUseDarkMode trivially but it will be much harder to use a WinRT API for either of those apps.

This might not be in the scope of Project Reunion itself, but it's where I was told to file feedback about it.

sylveon avatar May 21 '20 05:05 sylveon

If this isn't the place to request raw Win32 APIs, feel free to redirect me to the right place (except if that place is the Feedback Hub, my confidence in it has been reduced to 0)

sylveon avatar May 21 '20 06:05 sylveon

Project Reunion is about making APIs available to all apps - no matter which language, UX framework, runtime, or packaging system you use. WinUI-specific APIs would go in the WinUI repo.

We're still planning out which language projections to add - issue #18 has a proposed projection of an IDL based type for "flat C." Can you add comments / bumps to it so we can get a sense of which projections are important? See also issues tagged with "projection" for others folks have asked for.

Some Project Reunion APIs will also be "flat C to start" (ie: direct exports from the DLL with an associated header & import library) and then also get a metadata wrapper for languages & runtimes whose FFI is cumbersome.

Can you also file an issue in the cppwinrt repo for compilation times? (@kennykerr)

jonwis avatar May 21 '20 17:05 jonwis

Of course, I'm not opposed to providing a WinRT projection as well, I just believe that stabilizing the Win32 APIs would be best, as there are already existing users of those in the wild, and providing a guarantee the API won't break or be removed from under their feet would be best. It's also much simpler for those who can't use existing projections to use those.

Documenting and then wrapping those APIs in a WinRT class would also take less time than reimplementing them in WinRT.

sylveon avatar May 21 '20 18:05 sylveon

As for the compilation times, it's more of an inherent issue with C++ compilers, should be somewhat fixed when modules support is enabled in C++/WinRT.

sylveon avatar May 21 '20 18:05 sylveon

Aha! Check out the UISettings type from your Win32 apps, like this (C++/WinRT) example:

winrt::Windows::UI::ViewManagement::UISettings settings;
auto fg = settings.GetColorValue(winrt::Windows::UI::ViewManagement::UIColorType::Foreground);
auto bg = settings.GetColorValue(winrt::Windows::UI::ViewManagement::UIColorType::Background);

Apps can listen to changes to this setting on the UISettings.ColorValuesChanged event. There's also the (missing a verb) UIElementColor method, which you can for specific colors of UX components.

While you can't ask "are you dark/light/custom mode", you can definitely get the set of colors used by Windows to theme its own UX elements, which would let your apps be consistent.

jonwis avatar Jul 13 '20 21:07 jonwis

That certainly can work if you do your own custom drawing, but it doesn't cover cases where your UI kit has a simple dark/light toggle, where you have to guesstimate if bg is dark or light, neither does it cover the case where your app uses common controls or context menus with no custom drawing.

For example, XAML islands supports dark/light theming according to user preferences, but it doesn't update the theme when the user changes it in settings, so when my app receives WM_SETTINGCHANGE, I manually call the undocumented ShouldAppsUseDarkMode function and update the RequestedTheme on the XAML content appropriately:

https://github.com/TranslucentTB/TranslucentTB/blob/d8fa18512b11405bdacf93d463fb4b500de69b62/TranslucentTB/uwp/xamlpagehost.hpp#L59-L70

Also, if your app has a tray icon, you may want to know if the system uses a light or dark theme (not the apps), to choose the appropriate tray icon color (a white tray icon for the dark theme, and a black tray icon for the light theme)

sylveon avatar Jul 14 '20 01:07 sylveon

I'm getting ready to support Windows 11 in a Win32 app, and the Windows 11 developer documentation encourages developers to "Support Dark and Light themes."

My app's styling needs are very minimal - just the title bar - but it seems I will still need to resort to undocumented APIs. I hope this can be resolved soon.

rgwood avatar Jul 29 '21 04:07 rgwood

My app's styling needs are very minimal - just the title bar - but it seems I will still need to resort to undocumented APIs.

DWMWA_CAPTION_COLOR https://twitter.com/zodiacon/status/1416734060278341633

ghost avatar Jul 30 '21 14:07 ghost

It's not undocumented, I found it in the latest insider preview SDK (build 22000).

zodiacon avatar Aug 04 '21 07:08 zodiacon

@zodiacon yes, for information bellow this is the DWMWINDOWATTRIBUTE flags diff in the Windows 11 (Version 10.0.22000.0) preview SDK

enum DWMWINDOWATTRIBUTE
{
    DWMWA_NCRENDERING_ENABLED = 1,              // [get] Is non-client rendering enabled/disabled
    DWMWA_NCRENDERING_POLICY,                   // [set] DWMNCRENDERINGPOLICY - Non-client rendering policy
    DWMWA_TRANSITIONS_FORCEDISABLED,            // [set] Potentially enable/forcibly disable transitions
    DWMWA_ALLOW_NCPAINT,                        // [set] Allow contents rendered in the non-client area to be visible on the DWM-drawn frame.
    DWMWA_CAPTION_BUTTON_BOUNDS,                // [get] Bounds of the caption button area in window-relative space.
    DWMWA_NONCLIENT_RTL_LAYOUT,                 // [set] Is non-client content RTL mirrored
    DWMWA_FORCE_ICONIC_REPRESENTATION,          // [set] Force this window to display iconic thumbnails.
    DWMWA_FLIP3D_POLICY,                        // [set] Designates how Flip3D will treat the window.
    DWMWA_EXTENDED_FRAME_BOUNDS,                // [get] Gets the extended frame bounds rectangle in screen space
    DWMWA_HAS_ICONIC_BITMAP,                    // [set] Indicates an available bitmap when there is no better thumbnail representation.
    DWMWA_DISALLOW_PEEK,                        // [set] Don't invoke Peek on the window.
    DWMWA_EXCLUDED_FROM_PEEK,                   // [set] LivePreview exclusion information
    DWMWA_CLOAK,                                // [set] Cloak or uncloak the window
    DWMWA_CLOAKED,                              // [get] Gets the cloaked state of the window
    DWMWA_FREEZE_REPRESENTATION,                // [set] BOOL, Force this window to freeze the thumbnail without live update
    DWMWA_PASSIVE_UPDATE_MODE,                  // [set] BOOL, Updates the window only when desktop composition runs for other reasons
+   DWMWA_USE_HOSTBACKDROPBRUSH,                // [set] BOOL, Allows the use of host backdrop brushes for the window.
+   DWMWA_USE_IMMERSIVE_DARK_MODE = 20,         // [set] BOOL, Allows a window to either use the accent color, or dark, according to the user Color Mode preferences.
+   DWMWA_WINDOW_CORNER_PREFERENCE = 33,        // [set] WINDOW_CORNER_PREFERENCE, Controls the policy that rounds top-level window corners
+   DWMWA_BORDER_COLOR,                         // [set] COLORREF, The color of the thin border around a top-level window
+   DWMWA_CAPTION_COLOR,                        // [set] COLORREF, The color of the caption
+   DWMWA_TEXT_COLOR,                           // [set] COLORREF, The color of the caption text
+   DWMWA_VISIBLE_FRAME_BORDER_THICKNESS,       // [get] UINT, width of the visible border around a thick frame window
    DWMWA_LAST
};

So the DWMWA_USE_IMMERSIVE_DARK_MODE and the DWMWA_CAPTION_COLOR are documented on Windows 11. I dont really know what DWMWA_USE_HOSTBACKDROPBRUSH flag can do but maybe it's what MS Edge Dev uses for acrylic menus. I did the same diff for uxtheme.h but I can't see any dark mode traces for the Win32 controls. Did you see anything about it? I had thought that the other undocumented APIs mentioned by @sylveon would have been made public for Windows 11.

mveril avatar Aug 04 '21 13:08 mveril

I am still hopeful :)

zodiacon avatar Aug 04 '21 15:08 zodiacon

Please hold off on using these undocumented APIs/constants. There will be a supported path, stay tuned!

riverar avatar Aug 04 '21 15:08 riverar

Those DWM flags don't seem undocumented if they're part of the 22000 SDK though (well, the actual docs are missing because they're still preview APIs, but they're clearly meant for public usage).

@mveril DWMWA_USE_HOSTBACKDROPBRUSH allows Win32 apps to build and use host backdrop brushes from Windows.UI.Composition. There's some info about it here.

sylveon avatar Aug 04 '21 17:08 sylveon

Thanks for confirming they are not documented @sylveon. 😂

I'm just giving you a hard time, I know what you mean. Just trying to keep folks away from using the accent policy hacks. I believe there will be a few documented lines to solve all our Mica, corner, etc. needs.

riverar avatar Aug 04 '21 20:08 riverar

Ok @riverar maybe we are just too eager ! So wait and see… For rounded corners however this is already documented

mveril avatar Aug 04 '21 20:08 mveril

Windows 11 is releasing in a few days, still no documented APIs. Any updates?

lolametro avatar Sep 25 '21 16:09 lolametro

I think that the dark mode api's from uxtheme.dll should also change the predefined system colors (GetSysColors()) to return their equivalent darkmode variants when dark mode is enabled. For example, COLOR_WINDOW+1 should represent a dark gray/black brush when darkmode is enabled, and return the standard white when light mode is being used.

AzAgarampur avatar Sep 28 '21 04:09 AzAgarampur

With const UINT DWMWA_MICA_EFFFECT = 0x405; BOOL value = 1; DwmSetWindowAttribute(hwnd, DWMWA_MICA_EFFFECT, &value, sizeof(BOOL)); one can apply Mica effect to titlebar and areas covered by DwmExtendFrameIntoClientArea. Is this documented anywhere, where does this come from, does anyone have any idea?

Also, is there an exhaustive list of undocumented parameters for DwmGetWindowAttribute? Can we get the z-order of the window, for example, using that?

Thanks.

valinet avatar Oct 06 '21 16:10 valinet

So, some magic documentation just showed up for DWMWA_USE_IMMERSIVE_DARK_MODE, thanks to some person: https://github.com/MicrosoftDocs/sdk-api/blob/docs/sdk-api-src/content/dwmapi/ne-dwmapi-dwmwindowattribute.md#-field-dwmwa_use_immersive_dark_mode

Unfortunately, it seems wrong:

  • it mentions a constant DWMWA_USE_IMMERSIVE_DARK_MODE_BEFORE_20H1 that doesn't exist in the Windows SDK, someone just came up with it, and now everyone has it copy & pasted into their project
  • it says that scrollbars are made dark, even though they aren't unless you do SetWindowTheme(hwnd, L"DarkMode_Explorer", nullptr), which isn't documented anywhere
  • it doesn't even describe the function of the flag properly — it doesn't force dark theme when the window is inactive, it makes the active and inactive title bar responsive to the user's color preference

Obviously this needs cleaning up, but are these seemingly straightforward flags ever going to be properly documented at all? Naturally, it would be great to have more discoverable APIs in WASDK for these flags, but is there something wrong with documenting what's already in the SDK headers?

reflectronic avatar Nov 25 '21 23:11 reflectronic

@duncanmacmichael

riverar avatar Nov 26 '21 07:11 riverar

Thanks, @riverar. Looking into who the best contact is to update this documentation from our side.

duncanmacmichael avatar Dec 01 '21 01:12 duncanmacmichael

@duncanmacmichael connect with @stevewri and @leonardoblanco-ms

asklar avatar Dec 01 '21 03:12 asklar

Thanks @asklar, I was thinking more for the PM side where I wasn't sure who would be tackling this. :)

duncanmacmichael avatar Dec 01 '21 16:12 duncanmacmichael

I believe @Stevewri is the right PM for this (or he can say "not it" :) )

asklar avatar Dec 02 '21 06:12 asklar

@mveril added for Windows 11

enum DWMWINDOWATTRIBUTE
{
   ...
   DWMWA_USE_IMMERSIVE_DARK_MODE_BEFORE_20H1 = 19, // (for Windows 10 versions before 2004)
   DWMWA_MICA_EFFECT = 1029  // [set] BOOL
}

mcka-dev avatar Jan 28 '22 21:01 mcka-dev

DWMWA_USE_IMMERSIVE_DARK_MODE is listed in https://docs.microsoft.com/en-us/windows/win32/api/dwmapi/ne-dwmapi-dwmwindowattribute now, but with no further descriptions. Is it going to be documented?

driver1998 avatar Feb 22 '22 03:02 driver1998

So, some magic documentation just showed up for DWMWA_USE_IMMERSIVE_DARK_MODE, thanks to some person: https://github.com/MicrosoftDocs/sdk-api/blob/docs/sdk-api-src/content/dwmapi/ne-dwmapi-dwmwindowattribute.md#-field-dwmwa_use_immersive_dark_mode

Unfortunately, it seems wrong:

  • it mentions a constant DWMWA_USE_IMMERSIVE_DARK_MODE_BEFORE_20H1 that doesn't exist in the Windows SDK, someone just came up with it, and now everyone has it copy & pasted into their project
  • it says that scrollbars are made dark, even though they aren't unless you do SetWindowTheme(hwnd, L"DarkMode_Explorer", nullptr), which isn't documented anywhere
  • it doesn't even describe the function of the flag properly — it doesn't force dark theme when the window is inactive, it makes the active and inactive title bar responsive to the user's color preference

Obviously this needs cleaning up, but are these seemingly straightforward flags ever going to be properly documented at all? Naturally, it would be great to have more discoverable APIs in WASDK for these flags, but is there something wrong with documenting what's already in the SDK headers?

I documented it here back then https://github.com/MicrosoftDocs/sdk-api/pull/966.

I thought that DWMWA_USE_IMMERSIVE_DARK_MODE_BEFORE_20H1 was something Microsoft had internally as a valid name for the old value so I included it in case. My bad on that one.

AraHaan avatar Feb 28 '22 23:02 AraHaan