dark_mode.cc 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. // Copyright (c) 2022 Microsoft Inc. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE-CHROMIUM file.
  4. #include "shell/browser/win/dark_mode.h"
  5. #include <dwmapi.h> // DwmSetWindowAttribute()
  6. #include "base/win/windows_version.h"
  7. // This flag works since Win10 20H1 but is not documented until Windows 11
  8. #define DWMWA_USE_IMMERSIVE_DARK_MODE 20
  9. // This namespace contains code originally from
  10. // https://github.com/microsoft/terminal
  11. // governed by the MIT license and (c) Microsoft Corporation.
  12. namespace {
  13. // https://docs.microsoft.com/en-us/windows/win32/api/dwmapi/ne-dwmapi-dwmwindowattribute
  14. HRESULT TrySetWindowTheme(HWND hWnd, bool dark) {
  15. const BOOL isDarkMode = dark;
  16. HRESULT result = DwmSetWindowAttribute(hWnd, DWMWA_USE_IMMERSIVE_DARK_MODE,
  17. &isDarkMode, sizeof(isDarkMode));
  18. if (FAILED(result))
  19. return result;
  20. auto* os_info = base::win::OSInfo::GetInstance();
  21. auto const version = os_info->version();
  22. // Toggle the nonclient area active state to force a redraw (Win10 workaround)
  23. if (version < base::win::Version::WIN11) {
  24. HWND activeWindow = GetActiveWindow();
  25. SendMessage(hWnd, WM_NCACTIVATE, hWnd != activeWindow, 0);
  26. SendMessage(hWnd, WM_NCACTIVATE, hWnd == activeWindow, 0);
  27. }
  28. return S_OK;
  29. }
  30. } // namespace
  31. namespace electron::win {
  32. bool IsDarkModeSupported() {
  33. auto* os_info = base::win::OSInfo::GetInstance();
  34. auto const version = os_info->version();
  35. return version >= base::win::Version::WIN10_20H1;
  36. }
  37. void SetDarkModeForWindow(HWND hWnd) {
  38. ui::NativeTheme* theme = ui::NativeTheme::GetInstanceForNativeUi();
  39. bool dark =
  40. theme->ShouldUseDarkColors() && !theme->UserHasContrastPreference();
  41. TrySetWindowTheme(hWnd, dark);
  42. }
  43. } // namespace electron::win