Guest User

Screenshot window example

a guest
Nov 14th, 2023
373
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.53 KB | None | 0 0
  1. import win32gui
  2. import win32ui
  3. import win32con
  4.  
  5. def screenshot(hwnd = None):
  6.     from time import sleep
  7.     if not hwnd:
  8.         hwnd=win32gui.GetDesktopWindow()
  9.     l,t,r,b=win32gui.GetWindowRect(hwnd)
  10.     h=b-t
  11.     w=r-l
  12.     hDC = win32gui.GetWindowDC(hwnd)
  13.     myDC=win32ui.CreateDCFromHandle(hDC)
  14.     newDC=myDC.CreateCompatibleDC()
  15.  
  16.     myBitMap = win32ui.CreateBitmap()
  17.     myBitMap.CreateCompatibleBitmap(myDC, w, h)
  18.  
  19.     newDC.SelectObject(myBitMap)
  20.  
  21.     win32gui.SetForegroundWindow(hwnd)
  22.     sleep(.2) #lame way to allow screen to draw before taking shot
  23.     newDC.BitBlt((0,0),(w, h) , myDC, (0,0), win32con.SRCCOPY)
  24.     myBitMap.Paint(newDC)
  25.     myBitMap.SaveBitmapFile(newDC,'last_screenshot.bmp')
  26.  
  27. def _get_windows_bytitle(title_text, exact = False):
  28.     def _window_callback(hwnd, all_windows):
  29.         all_windows.append((hwnd, win32gui.GetWindowText(hwnd)))
  30.     windows = []
  31.     win32gui.EnumWindows(_window_callback, windows)
  32.     if exact:
  33.         return [hwnd for hwnd, title in windows if title_text == title]
  34.     else:
  35.         return [hwnd for hwnd, title in windows if title_text in title]
  36.  
  37. if __name__ == "__main__":
  38.     # First, find the window handle for "MyApplication"
  39.     hwnds = _get_windows_bytitle("firefox", exact=False)
  40.  
  41.     # Check if we found any windows
  42.     if hwnds:
  43.         # Take a screenshot of the first window we found
  44.         screenshot(hwnds[0])
  45.         print("Screenshot taken and saved to last_screenshot.bmp")
  46.     else:
  47.         print("No window found with the specified title.")
Advertisement
Add Comment
Please, Sign In to add comment