window.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. # This Python file uses the following encoding: utf-8
  2. # @author runhey
  3. # github https://github.com/runhey
  4. import cv2
  5. from numpy import frombuffer, uint8, array, random
  6. import numpy as np
  7. import time
  8. from win32gui import (GetWindowText, EnumWindows, FindWindow, FindWindowEx,
  9. IsWindow, GetWindowRect, GetWindowDC, DeleteObject,
  10. SetForegroundWindow, IsWindowVisible, GetDC, GetParent,
  11. EnumChildWindows)
  12. from win32ui import CreateDCFromHandle, CreateBitmap
  13. from win32con import SRCCOPY
  14. from module.exception import RequestHumanTakeover, ScriptError
  15. from module.logger import logger
  16. from module.device.handle import Handle, window_scale_rate
  17. class Window(Handle):
  18. def screenshot_window_background(self):
  19. """
  20. 后台截屏
  21. :return:
  22. """
  23. win_size = self.screenshot_size
  24. scale_rate = window_scale_rate()
  25. widthScreen = int(win_size[0] * scale_rate)
  26. heightScreen = int(win_size[1] * scale_rate)
  27. # 返回句柄窗口的设备环境,覆盖整个窗口,包括非客户区,标题栏,菜单,边框
  28. hwndDc = GetWindowDC(self.screenshot_handle_num)
  29. # 创建设备描述表
  30. mfcDc = CreateDCFromHandle(hwndDc)
  31. # 创建内存设备描述表
  32. saveDc = mfcDc.CreateCompatibleDC()
  33. # 创建位图对象准备保存图片
  34. saveBitMap = CreateBitmap()
  35. # 为bitmap开辟存储空间
  36. saveBitMap.CreateCompatibleBitmap(mfcDc, widthScreen, heightScreen)
  37. # 将截图保存到saveBitMap中
  38. saveDc.SelectObject(saveBitMap)
  39. # 保存bitmap到内存设备描述表
  40. saveDc.BitBlt((0, 0), (widthScreen, heightScreen), mfcDc, (0, 0), SRCCOPY)
  41. # 保存图像
  42. signedIntsArray = saveBitMap.GetBitmapBits(True)
  43. imgSrceen = frombuffer(signedIntsArray, dtype='uint8')
  44. imgSrceen.shape = (heightScreen, widthScreen, 4)
  45. # imgSrceen = cv2.cvtColor(imgSrceen, cv2.COLOR_BGRA2GRAY)
  46. imgSrceen = cv2.resize(imgSrceen, (win_size[0], win_size[1]))
  47. # 测试显示截图图片
  48. cv2.namedWindow('imgSrceen') # 命名窗口
  49. cv2.imshow("imgSrceen", imgSrceen) # 显示
  50. cv2.waitKey(0)
  51. cv2.destroyAllWindows()
  52. # 内存释放
  53. DeleteObject(saveBitMap.GetHandle())
  54. saveDc.DeleteDC()
  55. mfcDc.DeleteDC()
  56. return imgSrceen
  57. if __name__ == "__main__":
  58. w = Window(config='oas1')
  59. w.screenshot_window_background()