What window message applications receive on screen text size change

  • 8 months ago
Comment

ChatGPT
1 / 1

In Windows, when the screen text size (DPI scaling) changes, applications can receive a WM_DPICHANGED window message to indicate that the DPI has changed. This message is sent to the window procedure of the top-level window that is affected by the DPI change. The message includes information about the new DPI settings and the suggested window size to ensure proper rendering after the DPI change.

The WM_DPICHANGED message has the following parameters:

  • wParam: The new DPI of the window.
  • lParam: A pointer to a RECT structure that provides the suggested new size and position of the window's client area.

Here's how you can handle the WM_DPICHANGED message in a Windows application using the Win32 API:

c++
#include <Windows.h>

LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch (uMsg)
{
case WM_DPICHANGED:
// Retrieve new DPI from wParam
int newDpi = HIWORD(wParam);

// Retrieve suggested new window size from lParam
RECT* suggestedRect = (RECT*)lParam;

// Update window size and position based on the suggested rect
SetWindowPos(hwnd, NULL, suggestedRect->left, suggestedRect->top,
suggestedRect->right - suggestedRect->left,
suggestedRect->bottom - suggestedRect->top,
SWP_NOZORDER | SWP_NOACTIVATE);

// Redraw the window
InvalidateRect(hwnd, NULL, TRUE);
UpdateWindow(hwnd);
return 0;

// Handle other window messages...
}

return DefWindowProc(hwnd, uMsg, wParam, lParam);
}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPSTR lpCmdLine, int nCmdShow)

{
// Register window class
WNDCLASS wc = {0};
wc.lpfnWndProc = WindowProc;
wc.hInstance = hInstance;
wc.lpszClassName = L"MyWindowClass";
RegisterClass(&wc);

// Create window
HWND hwnd = CreateWindow(L"MyWindowClass", L"Window Title",
WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT,
CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, hInstance, NULL);

// Show and update window
ShowWindow(hwnd, nCmdShow);
UpdateWindow(hwnd);

// Message loop
MSG msg;
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}

return (int)msg.wParam;
}

This example demonstrates how to handle the WM_DPICHANGED message in a basic Win32 application. Keep in mind that proper handling of DPI scaling changes may require adjustments in various aspects of your application's layout, rendering, and user interface.