dark_mode.cc 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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 {
  32. namespace win {
  33. bool IsDarkModeSupported() {
  34. auto* os_info = base::win::OSInfo::GetInstance();
  35. auto const version = os_info->version();
  36. return version >= base::win::Version::WIN10_20H1;
  37. }
  38. void SetDarkModeForWindow(HWND hWnd) {
  39. ui::NativeTheme* theme = ui::NativeTheme::GetInstanceForNativeUi();
  40. bool dark =
  41. theme->ShouldUseDarkColors() && !theme->UserHasContrastPreference();
  42. TrySetWindowTheme(hWnd, dark);
  43. }
  44. } // namespace win
  45. } // namespace electron