Search code examples
winapivisual-c++mfcdialogdarkmode

Supporting dark mode for MFC dialog application (DwmSetWindowAttribute)


I might be going about this all wrong, but I stumbled on this article:

Support Dark and Light themes in Win32 apps

I followed the steps:

1/

#include <dwmapi.h>

2/

#ifndef DWMWA_USE_IMMERSIVE_DARK_MODE
#define DWMWA_USE_IMMERSIVE_DARK_MODE 20
#endif

3/

Call in InitInstance:

BOOL value = TRUE;
::DwmSetWindowAttribute(m_pMainWnd->GetSafeHwnd(),
                        DWMWA_USE_IMMERSIVE_DARK_MODE, 
                        &value, sizeof(value));

As you can see, I am using a CDialog based application.

4/ I added Dwmapi.lib.

It compiles fine. But when I run my application the title bar is not dark. Why?

A related question is that in the article it states:

This article provides examples of ways to detect system theme changes, and request a light or dark title bar for your Win32 application's window. It does not cover specifics of how to repaint and render your app UI using a Dark mode color set.

So how do we go about this for an MFC Dialog application?

Note that my Windows 11 PC is running in Dark Mode.


Solution

  • m_pMainWnd->GetSafeHwnd() returns NULL if run in InitInstance as window is not created yet. Try OnInitDialog and it will work.