macOS dark mode while window is in background

Hi,

I detect dark mode on macOS like following:

NSAppearance *appearance = NSApp.mainWindow.effectiveAppearance;
NSString *interface_style = appearance.name;

NSAppearanceName basicAppearance = [appearance bestMatchFromAppearancesWithNames:@[
            NSAppearanceNameAqua,
            NSAppearanceNameDarkAqua
        ]];

if([basicAppearance isEqualToString:NSAppearanceNameDarkAqua]){
  theme = "Adwaita:dark";

  dark_mode = TRUE;
}
    
if([interface_style isEqualToString:NSAppearanceNameDarkAqua]){
    theme = "Adwaita:dark";

    dark_mode = TRUE;
}else if([interface_style isEqualToString:NSAppearanceNameVibrantDark]){
   theme = "Adwaita:dark";

  dark_mode = TRUE;
}else if([interface_style isEqualToString:NSAppearanceNameAccessibilityHighContrastAqua]){
  theme = "HighContrast";
}else if([interface_style isEqualToString:NSAppearanceNameAccessibilityHighContrastDarkAqua]){
  theme = "HighContrast:dark";

  dark_mode = TRUE;
}else if([interface_style isEqualToString:NSAppearanceNameAccessibilityHighContrastVibrantDark]){
  theme = "HighContrast:dark";

  dark_mode = TRUE;
}

But this doesn't work if my window is in background. As the application window is put into background, it loses dark mode. Howto fix it?

regards, Joël

Answered by joel2001k in 821109022

interface_style was in this case null so I test it for being empty. now.

if([interface_style length] != 0){
  // ...
}

Isn't there a method in the app delegate in which you should set this up, so trait change or something? Then fire off a notification to make the change?

Also, I think you can shorten and simplify this code a little (written in a text editor and may not be 100% correct):

NSAppearance *appearance = NSApp.mainWindow.effectiveAppearance;
NSAppearanceName basicAppearance = [appearance bestMatchFromAppearancesWithNames:@[
	NSAppearanceNameAqua,
	NSAppearanceNameDarkAqua
]];

if([basicAppearance isEqualToString:NSAppearanceNameDarkAqua]){
	theme = "Adwaita:dark";
	dark_mode = TRUE;
}

switch(appearance.name) {
case NSAppearanceNameDarkAqua:
case NSAppearanceNameVibrantDark:
	theme = "Adwaita:dark";
	dark_mode = TRUE;
	break;
case NSAppearanceNameAccessibilityHighContrastAqua:
	theme = "HighContrast";
	break;
case NSAppearanceNameAccessibilityHighContrastDarkAqua:
case NSAppearanceNameAccessibilityHighContrastVibrantDark:
	theme = "HighContrast:dark";
	dark_mode = TRUE;
	break;
default:
	theme = "???";
}
Accepted Answer

interface_style was in this case null so I test it for being empty. now.

if([interface_style length] != 0){
  // ...
}
macOS dark mode while window is in background
 
 
Q