dark_mode.cc 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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. return S_OK;
  21. }
  22. } // namespace
  23. namespace electron::win {
  24. bool IsDarkModeSupported() {
  25. auto* os_info = base::win::OSInfo::GetInstance();
  26. auto const version = os_info->version();
  27. return version >= base::win::Version::WIN10_20H1;
  28. }
  29. void SetDarkModeForWindow(HWND hWnd) {
  30. ui::NativeTheme* theme = ui::NativeTheme::GetInstanceForNativeUi();
  31. bool dark =
  32. theme->ShouldUseDarkColors() && !theme->UserHasContrastPreference();
  33. TrySetWindowTheme(hWnd, dark);
  34. }
  35. } // namespace electron::win