electron/shell/browser/win/dark_mode.cc
Michaela Laurencin 4c7c0b41c2
feat: add immersive dark mode on windows (#33624)
* feat: add immersive dark mode

* fix syntax and add header

* add me

* Update fuses.json5

* fix: redraw title bar on dark mode change

* chore: SetWindowTheme doesn't seem to be needed

* chore: separate out Win 10 dark mode implementation

* final touches

* final touches

* chore: limit Win 10 to >= 20H1 and drop fuse

* fix types

* fix lint

Co-authored-by: Micha Hanselmann <micha.hanselmann@gmail.com>
Co-authored-by: David Sanders <dsanders11@ucsbalum.com>
2022-06-14 12:27:28 -04:00

64 lines
1.8 KiB
C++

// Copyright (c) 2022 Microsoft Inc. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-CHROMIUM file.
#include "shell/browser/win/dark_mode.h"
#include <dwmapi.h> // DwmSetWindowAttribute()
#include "base/win/windows_version.h"
// This flag works since Win10 20H1 but is not documented until Windows 11
#define DWMWA_USE_IMMERSIVE_DARK_MODE 20
// This namespace contains code originally from
// https://github.com/microsoft/terminal
// governed by the MIT license and (c) Microsoft Corporation.
namespace {
// https://docs.microsoft.com/en-us/windows/win32/api/dwmapi/ne-dwmapi-dwmwindowattribute
HRESULT TrySetWindowTheme(HWND hWnd, bool dark) {
const BOOL isDarkMode = dark;
HRESULT result = DwmSetWindowAttribute(hWnd, DWMWA_USE_IMMERSIVE_DARK_MODE,
&isDarkMode, sizeof(isDarkMode));
if (FAILED(result))
return result;
auto* os_info = base::win::OSInfo::GetInstance();
auto const version = os_info->version();
// Toggle the nonclient area active state to force a redraw (Win10 workaround)
if (version < base::win::Version::WIN11) {
HWND activeWindow = GetActiveWindow();
SendMessage(hWnd, WM_NCACTIVATE, hWnd != activeWindow, 0);
SendMessage(hWnd, WM_NCACTIVATE, hWnd == activeWindow, 0);
}
return S_OK;
}
} // namespace
namespace electron {
namespace win {
bool IsDarkModeSupported() {
auto* os_info = base::win::OSInfo::GetInstance();
auto const version = os_info->version();
return version >= base::win::Version::WIN10_20H1;
}
void SetDarkModeForWindow(HWND hWnd) {
ui::NativeTheme* theme = ui::NativeTheme::GetInstanceForNativeUi();
bool dark =
theme->ShouldUseDarkColors() && !theme->UserHasContrastPreference();
TrySetWindowTheme(hWnd, dark);
}
} // namespace win
} // namespace electron