ra1nty / DXcam

A Python high-performance screen capture library for Windows using Desktop Duplication API
MIT License
504 stars 70 forks source link

Handy conversion from screen coordinates to dx outputs #97

Open lovettchris opened 4 months ago

lovettchris commented 4 months ago

I had to write this code to convert from screen coordinates (returned for example from win32gui.GetWindowRect) to find the matching dx device output. It would be nice if dxcam could do this form me so I just specify a region in screen coordinates and it finds the appropriate device and output.

    def find_output(self, region: List[int]) -> Tuple[int, int]:
        x, y, w, h = region
        p_adapters = enum_dxgi_adapters()
        for i, p_adapter in enumerate(p_adapters):
            device = Device(p_adapter)
            p_outputs = device.enum_outputs()
            for j, p_output in enumerate(p_outputs):
                output = Output(p_output)
                left = output.desc.DesktopCoordinates.left
                top = output.desc.DesktopCoordinates.top
                width, height = output.resolution
                # if the region is inside the output then return this monitor
                if left <= x and x <= left + width and top <= y and y <= top + height:
                    # raise exception if the bounds overlaps monitors
                    if x + w > left + width or y + h > top + height:
                        raise Exception(f"Region {region} overlaps multiple monitors")
                    # adjust region to be relative to this monitor
                    self._region = [x - left, y - top, w, h]
                    return i, j
        raise Exception(f"Monitor containing region {region} not found")
lovettchris commented 2 months ago

I've implemented this in https://github.com/lovettchris/wincam