Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix Screengrab DPI scaling on Windows 10 version 1607+ #4000

Merged
merged 3 commits into from Sep 30, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
22 changes: 22 additions & 0 deletions src/display.c
Expand Up @@ -319,6 +319,8 @@ PyImaging_DisplayModeWin32(PyObject* self, PyObject* args)
/* -------------------------------------------------------------------- */
/* Windows screen grabber */

typedef HANDLE(__stdcall* Func_SetThreadDpiAwarenessContext)(HANDLE);

PyObject*
PyImaging_GrabScreenWin32(PyObject* self, PyObject* args)
{
Expand All @@ -329,6 +331,9 @@ PyImaging_GrabScreenWin32(PyObject* self, PyObject* args)
HDC screen, screen_copy;
DWORD rop;
PyObject* buffer;
HANDLE dpiAwareness;
HMODULE user32;
Func_SetThreadDpiAwarenessContext SetThreadDpiAwarenessContext_function;

if (!PyArg_ParseTuple(args, "|ii", &includeLayeredWindows, &all_screens))
return NULL;
Expand All @@ -339,6 +344,17 @@ PyImaging_GrabScreenWin32(PyObject* self, PyObject* args)
screen = CreateDC("DISPLAY", NULL, NULL, NULL);
screen_copy = CreateCompatibleDC(screen);

// added in Windows 10 (1607)
// loaded dynamically to avoid link errors
user32 = LoadLibraryA("User32.dll");
SetThreadDpiAwarenessContext_function =
(Func_SetThreadDpiAwarenessContext)
GetProcAddress(user32, "SetThreadDpiAwarenessContext");
if (SetThreadDpiAwarenessContext_function != NULL) {
// DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE = ((DPI_CONTEXT_HANDLE)-3)
dpiAwareness = SetThreadDpiAwarenessContext_function((HANDLE) -3);
}

if (all_screens) {
x = GetSystemMetrics(SM_XVIRTUALSCREEN);
y = GetSystemMetrics(SM_YVIRTUALSCREEN);
Expand All @@ -349,6 +365,12 @@ PyImaging_GrabScreenWin32(PyObject* self, PyObject* args)
height = GetDeviceCaps(screen, VERTRES);
}

if (SetThreadDpiAwarenessContext_function != NULL) {
SetThreadDpiAwarenessContext_function(dpiAwareness);
}

FreeLibrary(user32);

bitmap = CreateCompatibleBitmap(screen, width, height);
if (!bitmap)
goto error;
Expand Down