| 1 |
''' |
| 2 |
https://docs.microsoft.com/en-us/windows/desktop/api/wingdi/nf-wingdi-bitblt |
| 3 |
https://www.bugs.python.org/issue33656 |
| 4 |
''' |
| 5 |
|
| 6 |
from os import getpid |
| 7 |
from os.path import join |
| 8 |
from ctypes import windll, c_int, addressof |
| 9 |
|
| 10 |
from win32gui import GetDesktopWindow, GetWindowDC |
| 11 |
from win32api import GetSystemMetrics |
| 12 |
from win32ui import CreateDCFromHandle, CreateBitmap |
| 13 |
from win32con import ( |
| 14 |
SM_CXVIRTUALSCREEN, |
| 15 |
SM_CYVIRTUALSCREEN, |
| 16 |
SM_XVIRTUALSCREEN, |
| 17 |
SM_YVIRTUALSCREEN, |
| 18 |
SRCCOPY |
| 19 |
) |
| 20 |
|
| 21 |
from plyer.facades import Screenshot |
| 22 |
from plyer.platforms.win.storagepath import WinStoragePath |
| 23 |
|
| 24 |
|
| 25 |
class WinScreenshot(Screenshot): |
| 26 |
def __init__(self, file_path=None): |
| 27 |
default_path = join( |
| 28 |
WinStoragePath().get_pictures_dir(), 'screenshot.bmp' |
| 29 |
) |
| 30 |
super().__init__(file_path or default_path) |
| 31 |
|
| 32 |
def _set_dpi_aware(self, value): |
| 33 |
try: |
| 34 |
windll.shcore.SetProcessDpiAwareness(value) |
| 35 |
except (AttributeError, OSError): |
| 36 |
print('Could not set DPI awareness.') |
| 37 |
|
| 38 |
def _dpi_aware(self): |
| 39 |
|
| 40 |
|
| 41 |
try: |
| 42 |
process_handle = windll.kernel32.OpenProcess( |
| 43 |
0, |
| 44 |
False, |
| 45 |
getpid() |
| 46 |
) |
| 47 |
aware = c_int() |
| 48 |
windll.shcore.GetProcessDpiAwareness( |
| 49 |
process_handle, |
| 50 |
addressof(aware) |
| 51 |
) |
| 52 |
finally: |
| 53 |
|
| 54 |
windll.kernel32.CloseHandle(process_handle) |
| 55 |
return bool(aware) |
| 56 |
|
| 57 |
def _capture(self): |
| 58 |
|
| 59 |
|
| 60 |
|
| 61 |
old_awareness = self._dpi_aware() |
| 62 |
self._set_dpi_aware(True) |
| 63 |
|
| 64 |
|
| 65 |
width = GetSystemMetrics(SM_CXVIRTUALSCREEN) |
| 66 |
height = GetSystemMetrics(SM_CYVIRTUALSCREEN) |
| 67 |
|
| 68 |
|
| 69 |
handle_desktop = GetDesktopWindow() |
| 70 |
|
| 71 |
|
| 72 |
handle_context = GetWindowDC(handle_desktop) |
| 73 |
|
| 74 |
|
| 75 |
dev_ctx = CreateDCFromHandle(handle_context) |
| 76 |
|
| 77 |
|
| 78 |
dest_ctx = dev_ctx.CreateCompatibleDC() |
| 79 |
|
| 80 |
|
| 81 |
bmp = CreateBitmap() |
| 82 |
bmp.CreateCompatibleBitmap(dev_ctx, width, height) |
| 83 |
|
| 84 |
|
| 85 |
dest_ctx.SelectObject(bmp) |
| 86 |
|
| 87 |
|
| 88 |
dest_ctx.BitBlt( |
| 89 |
(0, 0), |
| 90 |
(width, height), |
| 91 |
dev_ctx, |
| 92 |
( |
| 93 |
GetSystemMetrics(SM_XVIRTUALSCREEN), |
| 94 |
GetSystemMetrics(SM_YVIRTUALSCREEN) |
| 95 |
), |
| 96 |
SRCCOPY |
| 97 |
) |
| 98 |
|
| 99 |
|
| 100 |
bmp.SaveBitmapFile(dest_ctx, self.file_path) |
| 101 |
|
| 102 |
|
| 103 |
self._set_dpi_aware(old_awareness) |
| 104 |
|
| 105 |
|
| 106 |
def instance(): |
| 107 |
return WinScreenshot() |