Skip to content

Instantly share code, notes, and snippets.

@hyrious
Last active June 7, 2025 12:22
Show Gist options
  • Save hyrious/c922c818d33d1f090cc658380cc0d1f2 to your computer and use it in GitHub Desktop.
Save hyrious/c922c818d33d1f090cc658380cc0d1f2 to your computer and use it in GitHub Desktop.
Get Windows scale correctly (like 150%).
#pragma comment(lib, "user32")
#pragma comment(lib, "gdi32")
#pragma comment(lib, "shcore")
#define NOMINMAX
#define WIN32_LEAN_AND_MEAN
#include <ShellScalingApi.h>
#include <Windows.h>
#include <cstdio>
auto main() -> int {
SetProcessDpiAwareness(PROCESS_PER_MONITOR_DPI_AWARE);
HDC hdc = GetDC(HWND_DESKTOP);
int dpi = GetDeviceCaps(hdc, LOGPIXELSY);
ReleaseDC(HWND_DESKTOP, hdc);
float scale = dpi * 1.0f / USER_DEFAULT_SCREEN_DPI;
printf("%f\n", scale);
}
// This file uses #pragma comment(lib), it needs MSVC's cl.exe to compile
// cl /nologo win32_scale.cpp
// If you want to listen to DPI changes, see the WM_DPICHANGED event
// https://learn.microsoft.com/en-us/windows/win32/hidpi/wm-dpichanged
@hyrious
Copy link
Author

hyrious commented Jun 7, 2025

To render a window at high dpi, follow these steps:

int width = 1280, height = 720; // Your desired client rect size, I'm omitting scaling here.

int dpi = ...; // code above.
int style = WS_OVERLAPPEDWINDOW; // Should be the same as your window. But actually it seems doesn't matter.
int exStyle = 0;
RECT margin = {0};
AdjustWindowRectExForDpi(&margin, style, FALSE, exStyle, dpi); // The value of dpi is obtained by code above.
int marginX = margin.right - margin.left;
int marginY = margin.bottom - margin.top;

CreateWindowEx(
  exStyle, szWndClassName, title, style, x, y,
  width + marginX, height + marginY, // <--
  NULL, NULL, hInstance, NULL);

@hyrious
Copy link
Author

hyrious commented Jun 7, 2025

To enable dark mode, at least for the title bar and the system menu (right click on title bar), without self rendering those things, follow these steps:

// Enable dark mode system menu.
#pragma comment(lib, "uxtheme")
enum class PreferredAppMode {
  Default,
  AllowDark,
  ForceDark,
  ForceLight,
  Max
};
HMODULE hUxtheme = LoadLibrary("UxTheme.dll");
using TYPE_SetPreferredAppMode = PreferredAppMode(WINAPI *)(PreferredAppMode appMode);
static const TYPE_SetPreferredAppMode SetPreferredAppMode = (TYPE_SetPreferredAppMode)GetProcAddress(hUxtheme, MAKEINTRESOURCEA(135));
SetPreferredAppMode(PreferredAppMode::AllowDark);

// Enable dark title bar.
#pragma comment(lib, "dwmapi")
BOOL enabled = TRUE;
DwmSetWindowAttribute(hwnd, DWMWA_USE_IMMERSIVE_DARK_MODE, &enabled, sizeof(enabled));

Reference: https://source.chromium.org/chromium/chromium/src/+/main:base/win/dark_mode_support.cc

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment