Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions docs/source/release-history/v11.0.0.md
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,10 @@ constructs based on {py:class}`Iterable` (rather than {py:class}`Iterator`) will
If {py:meth}`mss.MSS.save` is given a template with `{date}` in it, the dates are now in the local time zone, instead of
UTC.

On Windows, monitor geometry and captures now use per-monitor DPI coordinates even when the process DPI awareness was
already set by the host application, which previously made monitors with a different scaling than the primary one
report wrong sizes (#219).

## Command-line changes

If the `--output` / `-o` flag is used with `{date}` fields, dates in the filename are now in the local time zone,
Expand Down
49 changes: 48 additions & 1 deletion src/mss/windows/gdi.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

import ctypes
import sys
from contextlib import contextmanager
from ctypes import POINTER, WINFUNCTYPE, Structure, WinError, _Pointer
from ctypes.wintypes import (
BOOL,
Expand Down Expand Up @@ -35,7 +36,7 @@
from mss.models import Monitor

if TYPE_CHECKING:
from collections.abc import Callable
from collections.abc import Callable, Iterator

from mss.models import CFunctionsErrChecked, Monitors, Region

Expand All @@ -49,6 +50,9 @@
CCHDEVICENAME = 32
MONITORINFOF_PRIMARY = 0x01
EDD_GET_DEVICE_INTERFACE_NAME = 0x00000001
# DPI_AWARENESS_CONTEXT pseudo-handles (Windows 10 1607+; V2 needs 1703+).
DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE = -3
DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2 = -4


class BITMAPINFOHEADER(Structure):
Expand Down Expand Up @@ -206,6 +210,7 @@ class MSSImplGdi(MSSImplementation):
"_dib_array",
"_dib_bits",
"_region_width_height",
"_set_thread_dpi_context",
"gdi32",
"user32",
}
Expand All @@ -218,6 +223,7 @@ def __init__(self) -> None:
self.gdi32 = ctypes.WinDLL("gdi32", use_last_error=True)
self._set_cfunctions()
self._set_dpi_awareness()
self._set_thread_dpi_context = self._get_set_thread_dpi_context()

# Available instance-specific variables
self._region_width_height: tuple[int, int] | None = None
Expand Down Expand Up @@ -267,7 +273,43 @@ def _set_dpi_awareness(self) -> None:
# Windows Vista, 7, 8, and Server 2012
self.user32.SetProcessDPIAware()

def _get_set_thread_dpi_context(self) -> Callable | None:
"""Return ``SetThreadDpiAwarenessContext`` when available (Windows 10 1607+), else ``None``."""
func = getattr(self.user32, "SetThreadDpiAwarenessContext", None)
if func is None:
return None
func.argtypes = [HANDLE]
func.restype = HANDLE
return func

@contextmanager
def _per_monitor_dpi(self) -> Iterator[None]:
"""Make the calling thread per-monitor DPI aware for the duration of the block.

``SetProcessDpiAwareness()`` fails with ``E_ACCESSDENIED`` when the process DPI mode was already set
(by the host executable's manifest, a GUI toolkit, or an earlier call). The process then stays
system-DPI aware and Windows reports monitor sizes scaled by the primary monitor's DPI (issue #219).
A thread-level DPI context still works in that case, and restoring the previous context afterwards
leaves the host application's DPI behaviour untouched.
"""
set_context = self._set_thread_dpi_context
previous = None
if set_context is not None:
previous = set_context(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2)
if not previous:
# V2 is unknown before Windows 10 1703: fall back to V1.
previous = set_context(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE)
try:
yield
finally:
if previous:
set_context(previous) # type: ignore[misc]

def monitors(self) -> Monitors:
with self._per_monitor_dpi():
return self._monitors()

def _monitors(self) -> Monitors:
int_ = int
user32 = self.user32
get_system_metrics = user32.GetSystemMetrics
Expand Down Expand Up @@ -341,6 +383,11 @@ def callback(hmonitor: HMONITOR, _data: HDC, rect: LPRECT, _dc: LPARAM) -> bool:
return monitors

def grab(self, region: Region, /) -> bytearray:
"""Retrieve all pixels from a capture region, with per-monitor DPI coordinates."""
with self._per_monitor_dpi():
return self._grab(region)

def _grab(self, region: Region, /) -> bytearray:
"""Retrieve all pixels from a capture region using CreateDIBSection.

Device contexts (srcdc / memdc) are acquired and released within each
Expand Down
82 changes: 82 additions & 0 deletions src/tests/test_windows.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

try:
import mss.windows
from mss.windows import gdi
from mss.windows.gdi import MSSImplGdi, _check_result, _check_result_with_last_error
except ImportError:
pytestmark = pytest.mark.skip
Expand Down Expand Up @@ -201,3 +202,84 @@ def test_thread_safety_regions() -> None:
lambda: run_child_thread_bbox(100, (0, 0, 100, 100)),
lambda: run_child_thread_bbox(100, (0, 0, 50, 1)),
)


class _FakeSetThreadDpiContext:
"""Records calls to ``SetThreadDpiAwarenessContext`` and returns canned previous contexts."""

def __init__(self, results: list[int | None]) -> None:
self.calls: list[int] = []
self._results = results

def __call__(self, context: int) -> int | None:
self.calls.append(context)
return self._results.pop(0) if self._results else 1


def _impl_with_dpi_setter(setter: object) -> MSSImplGdi:
impl = MSSImplGdi.__new__(MSSImplGdi)
impl._set_thread_dpi_context = setter # type: ignore[assignment]
return impl


def test_per_monitor_dpi_sets_and_restores_thread_context() -> None:
"""Issue #219: the thread is per-monitor DPI aware (V2) inside the block, and restored afterwards."""
previous = 0x12
setter = _FakeSetThreadDpiContext([previous])
impl = _impl_with_dpi_setter(setter)

with impl._per_monitor_dpi():
assert setter.calls == [gdi.DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2]

assert setter.calls == [gdi.DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2, previous]


def test_per_monitor_dpi_restores_thread_context_on_error() -> None:
previous = 0x12
setter = _FakeSetThreadDpiContext([previous])
impl = _impl_with_dpi_setter(setter)

with pytest.raises(RuntimeError), impl._per_monitor_dpi():
raise RuntimeError

assert setter.calls[-1] == previous


def test_per_monitor_dpi_falls_back_to_v1() -> None:
"""Before Windows 10 1703, the V2 context is rejected (NULL): fall back to per-monitor V1."""
previous = 0x12
setter = _FakeSetThreadDpiContext([None, previous])
impl = _impl_with_dpi_setter(setter)

with impl._per_monitor_dpi():
pass

assert setter.calls == [
gdi.DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2,
gdi.DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE,
previous,
]


def test_per_monitor_dpi_without_api_is_noop() -> None:
"""On Windows versions without ``SetThreadDpiAwarenessContext`` nothing is called."""
impl = _impl_with_dpi_setter(None)
with impl._per_monitor_dpi():
pass


def test_monitors_restore_thread_dpi_context() -> None:
"""``monitors()`` must leave the caller's thread DPI awareness unchanged."""
user32 = ctypes.WinDLL("user32")
try:
get_ctx = user32.GetThreadDpiAwarenessContext
are_equal = user32.AreDpiAwarenessContextsEqual
except AttributeError:
pytest.skip("Thread DPI awareness contexts need Windows 10 1607+")
get_ctx.restype = ctypes.c_void_p
are_equal.argtypes = [ctypes.c_void_p, ctypes.c_void_p]

before = get_ctx()
with mss.MSS() as sct:
assert len(sct.monitors) >= 2 # The "all monitors" entry plus at least one monitor.
assert are_equal(before, get_ctx())