Created
February 6, 2025 18:30
-
-
Save amanyadev/6b3094e30313851252b5d864655df675 to your computer and use it in GitHub Desktop.
How to create native dark menu's using the Win32 API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// DarkMode.h | |
#pragma once | |
/** | |
* @brief Windows Dark Mode Menu Controller | |
* | |
* Provides functionality to force dark mode on Windows menus using the UxTheme API. | |
* This implementation uses undocumented Windows functions to achieve consistent | |
* dark mode appearance across the application's menus. | |
* | |
* @author Aman Yadav | |
* @date February 2025 | |
*/ | |
#ifndef DARK_MODE_H | |
#define DARK_MODE_H | |
#include <Windows.h> | |
namespace DarkMode { | |
/** | |
* @brief Application theme modes | |
*/ | |
enum class PreferredAppMode { | |
Default, ///< System default theme | |
AllowDark, ///< Allow dark mode if system uses it | |
ForceDark, ///< Always use dark mode | |
ForceLight, ///< Always use light mode | |
Max ///< Enum boundary | |
}; | |
/** | |
* @brief Initialize dark mode for application menus | |
* @return true if dark mode was successfully initialized | |
*/ | |
bool InitializeDarkMode(); | |
} | |
#endif // DARK_MODE_H | |
// DarkMode.cpp | |
#include "DarkMode.h" | |
#include <Uxtheme.h> | |
namespace { | |
using fnSetPreferredAppMode = DarkMode::PreferredAppMode(WINAPI*)(DarkMode::PreferredAppMode appMode); | |
using fnFlushMenuThemes = void(WINAPI*)(); | |
fnSetPreferredAppMode pfnSetPreferredAppMode = nullptr; | |
fnFlushMenuThemes pfnFlushMenuThemes = nullptr; | |
} | |
namespace DarkMode { | |
bool InitializeDarkMode() { | |
HMODULE hUxTheme = LoadLibraryEx(L"uxtheme.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); | |
if (!hUxTheme) { | |
return false; | |
} | |
pfnFlushMenuThemes = reinterpret_cast<fnFlushMenuThemes>( | |
GetProcAddress(hUxTheme, MAKEINTRESOURCEA(136))); | |
pfnSetPreferredAppMode = reinterpret_cast<fnSetPreferredAppMode>( | |
GetProcAddress(hUxTheme, MAKEINTRESOURCEA(135))); | |
if (!pfnFlushMenuThemes || !pfnSetPreferredAppMode) { | |
FreeLibrary(hUxTheme); | |
return false; | |
} | |
pfnSetPreferredAppMode(PreferredAppMode::ForceDark); | |
pfnFlushMenuThemes(); | |
return true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment