Exemple #1
0
 def GetScreenImg(self):
     """
     Gets the screen of the window referenced by self.hwnd
     """
     if self.hwnd is None:
         raise Exception(
             "HWND is none. HWND not called or invalid window name provided."
         )
     self.l, self.t, self.r, self.b = win32gui.GetWindowRect(self.hwnd)
     # Remove border around window (8 pixels on each side)
     # Remove 4 extra pixels from left and right 16 + 8 = 24
     w = self.r - self.l - self.br - self.bl
     # Remove border on top and bottom (31 on top 8 on bottom)
     # Remove 12 extra pixels from bottom 39 + 12 = 51
     h = self.b - self.t - self.bt - self.bb
     wDC = win32gui.GetWindowDC(self.hwnd)
     dcObj = win32ui.CreateDCFromHandle(wDC)
     cDC = dcObj.CreateCompatibleDC()
     dataBitMap = win32ui.CreateBitmap()
     dataBitMap.CreateCompatibleBitmap(dcObj, w, h)
     cDC.SelectObject(dataBitMap)
     # First 2 tuples are top-left and bottom-right of destination
     # Third tuple is the start position in source
     cDC.BitBlt((0, 0), (w, h), dcObj, (self.bl, self.bt), win32con.SRCCOPY)
     bmInfo = dataBitMap.GetInfo()
     im = np.frombuffer(dataBitMap.GetBitmapBits(True), dtype=np.uint8)
     dcObj.DeleteDC()
     cDC.DeleteDC()
     win32gui.ReleaseDC(self.hwnd, wDC)
     win32gui.DeleteObject(dataBitMap.GetHandle())
     # Bitmap has 4 channels like: BGRA. Discard Alpha and flip order to RGB
     # 31 pixels from border on top, 8 on bottom
     # 8 pixels from border on the left and 8 on right
     # Remove 1 additional pixel from left and right so size is 1278 | 9
     # Remove 14 additional pixels from bottom so size is 786 | 6
     # return im.reshape(bmInfo['bmHeight'], bmInfo['bmWidth'], 4)[31:-22, 9:-9, -2::-1]
     # For 800x600 images:
     # Remove 12 pixels from bottom + border
     # Remove 4 pixels from left and right + border
     return im.reshape(bmInfo["bmHeight"], bmInfo["bmWidth"], 4)[:, :,
                                                                 -2::-1]
Exemple #2
0
    def background_screenshot(self):
        # Get infromation of the windows program
        window_handle = win32gui.FindWindow(None, self.program_title.lower())
        if window_handle == 0:
            return None

        bbox = win32gui.GetWindowRect(window_handle)

        width = bbox[2] - bbox[0]
        height = bbox[3] - bbox[1]

        # setup screenshot
        wdc = win32gui.GetWindowDC(window_handle)
        dcobj = win32ui.CreateDCFromHandle(wdc)
        cdc = dcobj.CreateCompatibleDC()
        databitmap = win32ui.CreateBitmap()
        databitmap.CreateCompatibleBitmap(dcobj, width, height)
        cdc.SelectObject(databitmap)

        # Take Screenshot
        windll.user32.PrintWindow(window_handle, cdc.GetSafeHdc(), 0)

        # Convert bitmap to PIL image
        bmpinfo = databitmap.GetInfo()
        bmpstr = databitmap.GetBitmapBits(True)

        img = Image.frombuffer('RGB',
                               (bmpinfo['bmWidth'], bmpinfo['bmHeight']),
                               bmpstr, 'raw', 'BGRX', 0, 1)
        if self.debug:
            databitmap.SaveBitmapFile(cdc, 'screenshot.bmp')

        # Clsoe handlers
        win32gui.DeleteObject(databitmap.GetHandle())
        cdc.DeleteDC()
        dcobj.DeleteDC()
        win32gui.ReleaseDC(window_handle, wdc)

        # convert PIL image to ndarray required for opencv
        open_cv_image = np.array(img)
        return open_cv_image
def hdms_this(hwnd, left, top, right, bot):
    w = right - left
    h = bot - top

    hwndDC = win32gui.GetWindowDC(hwnd)
    mfcDC = win32ui.CreateDCFromHandle(hwndDC)
    saveDC = mfcDC.CreateCompatibleDC()

    saveBitMap = win32ui.CreateBitmap()
    saveBitMap.CreateCompatibleBitmap(mfcDC, w, h)

    saveDC.SelectObject(saveBitMap)

    # Change the line below depending on whether you want the whole window
    # or just the client area.
    # result = windll.user32.PrintWindow(hwnd, saveDC.GetSafeHdc(), 1)
    result = windll.user32.PrintWindow(hwnd, saveDC.GetSafeHdc(), 0)
    # print result

    bmpinfo = saveBitMap.GetInfo()
    bmpstr = saveBitMap.GetBitmapBits(True)

    im = Image.frombuffer(
        'RGB',
        (bmpinfo['bmWidth'], bmpinfo['bmHeight']),
        bmpstr, 'raw', 'BGRX', 0, 1)

    win32gui.DeleteObject(saveBitMap.GetHandle())
    saveDC.DeleteDC()
    mfcDC.DeleteDC()
    win32gui.ReleaseDC(hwnd, hwndDC)

    if result == 1:
        # temp_file = "{0}/{1}.png".format(gc.temp_folder, str(uuid.uuid4()))
        # PrintWindow Succeeded
        # im.save(temp_file)
        # return temp_file

        return im

    return
Exemple #4
0
def window_capture():
    # 获取桌面句柄和桌面的宽度和高度
    desktop_h = win32gui.GetDesktopWindow()
    width = win32api.GetSystemMetrics(win32con.SM_CXVIRTUALSCREEN)
    height = win32api.GetSystemMetrics(win32con.SM_CYVIRTUALSCREEN)
    # 创建设备描述表
    desktop_dc = win32gui.GetWindowDC(desktop_h)
    img_dc = win32ui.CreateDCFromHandle(desktop_dc)
    # 创建一个内存设备描述表
    save_dc = img_dc.CreateCompatibleDC()
    # 创建位图对象
    capture = win32ui.CreateBitmap()
    capture.CreateCompatibleBitmap(img_dc, width, height)
    save_dc.SelectObject(capture)
    # 保存图片
    save_dc.BitBlt((0, 0), (width, height), img_dc, (0, 0), win32con.SRCCOPY)
    capture.SaveBitmapFile(save_dc, './yys/shot.png')
    # 释放内存
    save_dc.DeleteDC()
    win32gui.DeleteObject(capture.GetHandle())
    win32gui.ReleaseDC(desktop_h, desktop_dc)
Exemple #5
0
 def highLight(self):
     """高亮此区域
     """
     hwnd = win32gui.GetDesktopWindow()
     hDesktopDC = win32gui.GetWindowDC(hwnd)
     oldRop2 = ctypes.windll.gdi32.SetROP2(hDesktopDC,
                                           win32con.R2_NOTXORPEN)
     newPen = win32gui.CreatePen(win32con.PS_SOLID, 3, 0)
     oldPen = win32gui.SelectObject(hDesktopDC, newPen)
     #在指示窗口周围显示闪烁矩形
     for i in range(2):
         win32gui.Rectangle(hDesktopDC, self._rect[0], self._rect[1],
                            self._rect[2], self._rect[3])
         time.sleep(0.2)
         win32gui.Rectangle(hDesktopDC, self._rect[0], self._rect[1],
                            self._rect[2], self._rect[3])
         time.sleep(0.3)
     ctypes.windll.gdi32.SetROP2(hDesktopDC, oldRop2)
     win32gui.SelectObject(hDesktopDC, oldPen)
     win32gui.DeleteObject(newPen)
     win32gui.ReleaseDC(hwnd, hDesktopDC)
Exemple #6
0
def get_background_image(handle):
    if handle == 0:
        return "../images/blank.bmp"
    hwnd = handle
    w = 960
    h = 540
    hwndDC = win32gui.GetWindowDC(hwnd)
    mfcDC = win32ui.CreateDCFromHandle(hwndDC)
    saveDC = mfcDC.CreateCompatibleDC()
    saveBitMap = win32ui.CreateBitmap()
    saveBitMap.CreateCompatibleBitmap(mfcDC, w, h)
    saveDC.SelectObject(saveBitMap)
    img_dc = mfcDC
    mem_dc = saveDC
    mem_dc.BitBlt((0, 0), (w, h), img_dc, (0, 0), win32con.SRCCOPY)
    saveBitMap.SaveBitmapFile(mem_dc, "../images/screenShot.bmp")
    win32gui.DeleteObject(saveBitMap.GetHandle())
    saveDC.DeleteDC()
    mfcDC.DeleteDC()
    win32gui.ReleaseDC(hwnd, hwndDC)
    return "../images/screenShot.bmp"
Exemple #7
0
def write_text(text=""):
    hwin = win32gui.GetDesktopWindow()
    hdc = win32gui.GetDC(hwin)

    # 텍스트 옵션
    font = win32ui.CreateFont({"name": "Arial", "height": 64, "weight": 400})
    oldFont = win32gui.SelectObject(hdc, font.GetSafeHandle())

    #win32gui.SetTextColor(hdc, win32api.RGB(0,0,0))
    #win32gui.SetBkColor(hdc, win32api.RGB(255, 255, 255))

    rect = win32gui.GetClientRect(hwin)
    win32gui.DrawText(
        hdc, text, len(text), rect, win32con.DT_BOTTOM | win32con.DT_RIGHT
        | win32con.DT_SINGLELINE | win32con.DT_WORDBREAK
        #win32con.DT_CENTER|win32con.DT_VCENTER|win32con.DT_SINGLELINE|win32con.DT_WORDBREAK
    )

    win32gui.SelectObject(hdc, oldFont)
    win32gui.DeleteObject(font.GetSafeHandle())
    win32gui.ReleaseDC(hwin, hdc)
Exemple #8
0
def take_screenshot(x0, y0, dx, dy):
    """
    Takes a screenshot of the region of the active window starting from
    (x0, y0) with width dx and height dy.
    """
    hwnd = win32gui.GetForegroundWindow()   # Window handle
    wDC = win32gui.GetWindowDC(hwnd)        # Window device context
    dcObj = win32ui.CreateDCFromHandle(wDC)
    cDC = dcObj.CreateCompatibleDC()

    dataBitMap = win32ui.CreateBitmap()     # PyHandle object
    dataBitMap.CreateCompatibleBitmap(dcObj, dx, dy)
    cDC.SelectObject(dataBitMap)
    cDC.BitBlt((0,0),(dx, dy) , dcObj, (x0, y0), win32con.SRCCOPY)
    image = dataBitMap.GetBitmapBits(1)

    dcObj.DeleteDC()
    cDC.DeleteDC()
    win32gui.ReleaseDC(hwnd, wDC)

    return Image.frombuffer("RGBA", (384, 448), image, "raw", "RGBA", 0, 1)
Exemple #9
0
 def OnInit(self):
     dll = ctypes.WinDLL('gdi32.dll')
     for idx, (hMon, hDC, (left, top, right, bottom)) in enumerate(win32api.EnumDisplayMonitors(None, None)):
         hDeskDC = win32gui.CreateDC(win32api.GetMonitorInfo(hMon)['Device'], None, None)
         bitmap = wx.Bitmap(right - left, bottom - top)
         hMemDC = wx.MemoryDC()
         hMemDC.SelectObject(bitmap)
         try:
             dll.BitBlt(hMemDC.GetHDC(), 0, 0, right - left, bottom - top, int(hDeskDC), 0, 0, win32con.SRCCOPY)
         finally:
             hMemDC.SelectObject(wx.NullBitmap)
         bitmap.SaveFile('screenshots/screenshot_%02d.bmp' % idx, wx.BITMAP_TYPE_BMP)
         win32gui.ReleaseDC(win32gui.GetDesktopWindow(), hDeskDC)
     im1 = Image.open('screenshots/screenshot_00.bmp', 'r')
     for idx, (hMon, hDC, (left, top, right, bottom)) in enumerate(win32api.EnumDisplayMonitors(None, None)):
         if idx == 0:
             continue
         im2 = Image.open('screenshots/screenshot_%02d.bmp' % idx, 'r')
         im1 = get_concat_h(im1, im2)
     im1.save('screenshots/screenshot.jpg')
     return True
Exemple #10
0
    def GrabScreen(self, region=None):
        """Quickly grab screen reigon using win32 libs

        Keyword Arguments:
            region {[tuple]} -- [left_offset, top_offset, xreigon, yreigon] (default: {None})

        Returns:
            [type] -- [cv2 image]
        """
        hwin = win32gui.GetDesktopWindow()

        if region:
            left, top, x2, y2 = region
            width = x2 - left + 1
            height = y2 - top + 1
        else:
            width = win32api.GetSystemMetrics(win32con.SM_CXVIRTUALSCREEN)
            height = win32api.GetSystemMetrics(win32con.SM_CYVIRTUALSCREEN)
            left = win32api.GetSystemMetrics(win32con.SM_XVIRTUALSCREEN)
            top = win32api.GetSystemMetrics(win32con.SM_YVIRTUALSCREEN)

        hwindc = win32gui.GetWindowDC(hwin)
        srcdc = win32ui.CreateDCFromHandle(hwindc)
        memdc = srcdc.CreateCompatibleDC()
        bmp = win32ui.CreateBitmap()
        bmp.CreateCompatibleBitmap(srcdc, width, height)
        memdc.SelectObject(bmp)
        memdc.BitBlt((0, 0), (width, height), srcdc, (left, top),
                     win32con.SRCCOPY)

        signedIntsArray = bmp.GetBitmapBits(True)
        img = np.fromstring(signedIntsArray, dtype='uint8')
        img.shape = (height, width, 4)

        srcdc.DeleteDC()
        memdc.DeleteDC()
        win32gui.ReleaseDC(hwin, hwindc)
        win32gui.DeleteObject(bmp.GetHandle())

        return img
Exemple #11
0
    def shot(cls,name= 'playing.png'):
        hwnd = win32gui.FindWindow(None, cls.processname)

        # Change the line below depending on whether you want the whole window
        # or just the client area. 
        left, top, right, bot = win32gui.GetClientRect(hwnd)
        #left, top, right, bot = win32gui.GetWindowRect(hwnd)
        w = right - left
        h = bot - top

        hwndDC = win32gui.GetWindowDC(hwnd)
        mfcDC  = win32ui.CreateDCFromHandle(hwndDC)
        saveDC = mfcDC.CreateCompatibleDC()

        saveBitMap = win32ui.CreateBitmap()
        saveBitMap.CreateCompatibleBitmap(mfcDC, w, h)

        saveDC.SelectObject(saveBitMap)

        # Change the line below depending on whether you want the whole window
        # or just the client area. 
        #result = windll.user32.PrintWindow(hwnd, saveDC.GetSafeHdc(), 1)
        result = windll.user32.PrintWindow(hwnd, saveDC.GetSafeHdc(), 0)

        bmpinfo = saveBitMap.GetInfo()
        bmpstr = saveBitMap.GetBitmapBits(True)

        im = Image.frombuffer(
            'RGB',
            (bmpinfo['bmWidth'], bmpinfo['bmHeight']),
            bmpstr, 'raw', 'BGRX', 0, 1)

        win32gui.DeleteObject(saveBitMap.GetHandle())
        saveDC.DeleteDC()
        mfcDC.DeleteDC()
        win32gui.ReleaseDC(hwnd, hwndDC)

        if result == 1:
            #PrintWindow Succeeded
            im.save("playing.png")
Exemple #12
0
def grab_screen(region=None):
    logger = log_grab_screen.get_logger('grab_screen')

    while True:
        try:
            hwin = win32gui.GetDesktopWindow()

            if region:
                left, top, x2, y2 = region
                width = x2 - left + 1
                height = y2 - top + 1
            else:
                width = win32api.GetSystemMetrics(win32con.SM_CXVIRTUALSCREEN)
                height = win32api.GetSystemMetrics(win32con.SM_CYVIRTUALSCREEN)
                left = win32api.GetSystemMetrics(win32con.SM_XVIRTUALSCREEN)
                top = win32api.GetSystemMetrics(win32con.SM_YVIRTUALSCREEN)

            hwindc = win32gui.GetWindowDC(hwin)
            srcdc = win32ui.CreateDCFromHandle(hwindc)
            memdc = srcdc.CreateCompatibleDC()
            bmp = win32ui.CreateBitmap()
            bmp.CreateCompatibleBitmap(srcdc, width, height)
            memdc.SelectObject(bmp)
            memdc.BitBlt((0, 0), (width, height), srcdc, (left, top),
                         win32con.SRCCOPY)

            signedIntsArray = bmp.GetBitmapBits(True)
            img = np.fromstring(signedIntsArray, dtype='uint8')
            img.shape = (height, width, 4)

            srcdc.DeleteDC()
            memdc.DeleteDC()
            win32gui.ReleaseDC(hwin, hwindc)
            win32gui.DeleteObject(bmp.GetHandle())

            return cv2.cvtColor(img, cv2.COLOR_BGRA2RGB)

        except Exception as e:
            # grab_screen(region)
            logger.error(e)
def get_window_shot(hwnd):
    # 对后台应用程序截图,程序窗口可以被覆盖,但如果最小化后只能截取到标题栏、菜单栏等。

    # 使用自定义的窗口边缘和大小设置
    dx = config.getint("Device", "EdgeOffsetX")
    dy = config.getint("Device", "EdgeOffsetY")
    w = config.getint("Device", "MainWidth")
    h = config.getint("Device", "MainHeight")
    window_w, window_h = detect_window_size(hwnd)
    if dx + w > window_w or dy + h > window_h:
        raise ValueError("截图区域超出窗口! 请检查配置文件")
    # logger.debug("截图: %dx%d at %dx%d", w, h, dx, dy)

    # 返回句柄窗口的设备环境、覆盖整个窗口,包括非客户区,标题栏,菜单,边框
    hwndDC = win32gui.GetWindowDC(hwnd)
    # 创建设备描述表
    mfcDC = win32ui.CreateDCFromHandle(hwndDC)
    # 创建内存设备描述表
    saveDC = mfcDC.CreateCompatibleDC()
    # 创建位图对象
    saveBitMap = win32ui.CreateBitmap()
    saveBitMap.CreateCompatibleBitmap(mfcDC, w, h)
    saveDC.SelectObject(saveBitMap)
    # 截图至内存设备描述表
    saveDC.BitBlt((0, 0), (w, h), mfcDC, (dx, dy), win32con.SRCCOPY)
    # 获取位图信息
    bmpinfo = saveBitMap.GetInfo()
    bmpdata = saveBitMap.GetBitmapBits(True)
    # 生成图像
    image_data = np.frombuffer(bmpdata, "uint8")
    image_data = image_data.reshape(
        (bmpinfo["bmHeight"], bmpinfo["bmWidth"], 4))
    image_data = cv.cvtColor(image_data, cv.COLOR_BGRA2BGR)
    # 内存释放
    win32gui.DeleteObject(saveBitMap.GetHandle())
    saveDC.DeleteDC()
    mfcDC.DeleteDC()
    win32gui.ReleaseDC(hwnd, hwndDC)

    return image_data
Exemple #14
0
def capture_inactive_window(hwnd, client_area_only=True):
    """指定窗口截图

    http://stackoverflow.com/questions/19695214/python-screenshot-of-inactive\
            -window-printwindow-win32gui

    需要做黑屏判断,printwindow失败会得到一个黑色的图
    """
    left, top, right, bottom = win32gui.GetWindowRect(hwnd)

    w = right - left
    h = bottom - top

    srcdc = win32gui.GetWindowDC(hwnd)
    memdc = win32ui.CreateDCFromHandle(srcdc)
    destdc = memdc.CreateCompatibleDC()

    bmp = win32ui.CreateBitmap()
    bmp.CreateCompatibleBitmap(memdc, w, h)
    destdc.SelectObject(bmp)

    windll.user32.PrintWindow(hwnd, destdc.GetSafeHdc(), 1 if client_area_only\
            else 0)

    bmp_info = bmp.GetInfo()
    bmp_bits = bmp.GetBitmapBits(True)

    # Only works in 32bit mode,
    # 虚拟机下有可能图形不是在 32 位模式的
    im = Image.frombuffer('RGB', (bmp_info['bmWidth'], bmp_info['bmHeight']),
                          bmp_bits, 'raw', 'BGRX', 0, 1)

    win32gui.DeleteObject(bmp.GetHandle())
    destdc.DeleteDC()
    memdc.DeleteDC()
    win32gui.ReleaseDC(hwnd, srcdc)

    windll.user32.UpdateWindow(hwnd)

    return im
    def capture(self, relative=(0, 0)):
        """
        Return a PIL image of the control.

        See PIL documentation to know what you can do with the resulting
        image.
        """
        left, top, right, bot = win32gui.GetWindowRect(self.handle)
        w = right - left
        h = bot - top

        hwndDC = win32gui.GetWindowDC(self.handle)
        mfcDC = win32ui.CreateDCFromHandle(hwndDC)
        saveDC = mfcDC.CreateCompatibleDC()

        saveBitMap = win32ui.CreateBitmap()
        saveBitMap.CreateCompatibleBitmap(mfcDC, w + relative[0],
                                          h + relative[1])

        saveDC.SelectObject(saveBitMap)
        saveDC.BitBlt(relative, (w, h), mfcDC, (left, top), win32con.SRCCOPY)

        bmpinfo = saveBitMap.GetInfo()
        bmpstr = saveBitMap.GetBitmapBits(True)
        img = Image.frombuffer('RGB',
                               (bmpinfo['bmWidth'], bmpinfo['bmHeight']),
                               bmpstr, 'raw', 'BGRX', 0, 1)
        """img_w, img_h = img.size
        #font = ImageFont.truetype('Operator Mono Lig.ttf', 20)
        font = ImageFont.truetype('arial.ttf', 100)
        mask = font.getmask('This is watermark text', mode='L')
        mask_w, mask_h = mask.size
        d = Image.core.draw(img.im, 0)
        d.draw_bitmap(((img_w - mask_w)/2, (img_h - mask_h)/2), mask, 100)"""

        win32gui.DeleteObject(saveBitMap.GetHandle())
        saveDC.DeleteDC()
        mfcDC.DeleteDC()
        win32gui.ReleaseDC(self.handle, hwndDC)
        return img
Exemple #16
0
def grab_frame(size=None):

    hwin = win32gui.GetDesktopWindow()

    if size:
        left, top, x, y  = size
        width= x - left + 1
        height= y - top +1

    else:
        width = win32api.GetSystemMetrics(win32con.SM_CXVIRTUALSCREEN)
        height = win32api.GetSystemMetrics(win32con.SM_CYVIRTUALSCREEN)
        left = win32api.GetSystemMetrics(win32con.SM_XVIRTUALSCREEN)
        top = win32api.GetSystemMetrics(win32con.SM_YVIRTUALSCREEN)



    hwindc = win32gui.GetWindowDC(hwin)
    srcdc = win32ui.CreateDCFromHandle(hwindc)
    memdc = srcdc.CreateCompatibleDC()
    bmp = win32ui.CreateBitmap()
    bmp.CreateCompatibleBitmap(srcdc, width, height)
    memdc.SelectObject(bmp)
    memdc.BitBlt((0, 0), (width, height), srcdc, (left, top), win32con.SRCCOPY)


    signedIntsArray = bmp.GetBitmapBits(True)

    img = np.fromstring(signedIntsArray, dtype='uint8')

    img.shape = (height, width, 4)

    srcdc.DeleteDC()
    memdc.DeleteDC()
    win32gui.ReleaseDC(hwin, hwindc)
    win32gui.DeleteObject(bmp.GetHandle())

    img_res = cv2.resize(img, (480,270))
    img_rgb = cv2.cvtColor(img_res, cv2.COLOR_BGRA2RGB)
    return img_rgb
def grab_screen(width=800, height=600):

    hwnd = win32gui.GetDesktopWindow()
    wDC = win32gui.GetWindowDC(hwnd)
    dcObj = win32ui.CreateDCFromHandle(wDC)
    cDC = dcObj.CreateCompatibleDC()
    dataBitMap = win32ui.CreateBitmap()
    dataBitMap.CreateCompatibleBitmap(dcObj, width, height)
    cDC.SelectObject(dataBitMap)
    cDC.BitBlt((0, 0), (width, height), dcObj, (0, 50), win32con.SRCCOPY)
    # dataBitMap.SaveBitmapFile(cDC, bmpfilenamename + str(0) + ".png")

    signedIntsArray = dataBitMap.GetBitmapBits(True)
    img = np.fromstring(signedIntsArray, dtype='uint8')
    img.shape = (height, width, 4)

    # Free Resources
    dcObj.DeleteDC()
    cDC.DeleteDC()
    win32gui.ReleaseDC(hwnd, wDC)
    win32gui.DeleteObject(dataBitMap.GetHandle())
    return img
Exemple #18
0
    def __init__(self, array, selectedKey):
        self.myArray = array
        hwnd = win32gui.FindWindow(None, 'Audition')

        left, top, right, bot = win32gui.GetWindowRect(hwnd)
        w = right - left
        h = bot - top

        wDC = win32gui.GetWindowDC(hwnd)
        dcObj = win32ui.CreateDCFromHandle(wDC)
        cDC = dcObj.CreateCompatibleDC()
        dataBitMap = win32ui.CreateBitmap()
        dataBitMap.CreateCompatibleBitmap(dcObj, w, h)
        cDC.SelectObject(dataBitMap)
        cDC.BitBlt((0, 0), (w, h), dcObj, (0, 0), win32con.SRCCOPY)
        dataBitMap.SaveBitmapFile(cDC, 'test.jpg')
        dcObj.DeleteDC()
        cDC.DeleteDC()
        win32gui.ReleaseDC(hwnd, wDC)
        win32gui.DeleteObject(dataBitMap.GetHandle())
        self.selectedKey = selectedKey
        self.cropSelected()
Exemple #19
0
def grab_screen(region=None, title=None):
    hwin = win32gui.GetDesktopWindow()
    if region:
        left,top,x2,y2 = region
        width = x2 - left + 1
        height = y2 - top + 1
    elif title:
        gtawin = win32gui.FindWindow(None, title)
        if not gtawin:
            raise Exception('window title not found')
        #get the bounding box of the window
        left, top, x2, y2 = win32gui.GetWindowRect(gtawin)
        width = x2 - left +1
        height = y2 - top +1
    else:
        width = win32api.GetSystemMetrics(win32con.SM_CXVIRTUALSCREEN)
        height = win32api.GetSystemMetrics(win32con.SM_CYVIRTUALSCREEN)
        left = win32api.GetSystemMetrics(win32con.SM_XVIRTUALSCREEN)
        top = win32api.GetSystemMetrics(win32con.SM_YVIRTUALSCREEN)

    hwindc = win32gui.GetWindowDC(hwin)
    srcdc = win32ui.CreateDCFromHandle(hwindc)
    memdc = srcdc.CreateCompatibleDC()
    bmp = win32ui.CreateBitmap()
    bmp.CreateCompatibleBitmap(srcdc, width, height)
    memdc.SelectObject(bmp)
    memdc.BitBlt((0, 0), (width, height), srcdc, (left, top), win32con.SRCCOPY)

    signedIntsArray = bmp.GetBitmapBits(True)
    img = np.frombuffer(signedIntsArray, dtype='uint8')
    img.shape = (height,width,4)

    srcdc.DeleteDC()
    memdc.DeleteDC()
    win32gui.ReleaseDC(hwin, hwindc)
    win32gui.DeleteObject(bmp.GetHandle())

    img = cv2.cvtColor(img, cv2.COLOR_BGRA2BGR)
    cv2.imwrite('n.png', img)
Exemple #20
0
    def _get_screen(self):
        """Get screen image from main window.

        :return: PIL.Image image from window.
        """
        if not self.parent_hwnd:
            return None
        while self.screen_locked:
            if self.last_frame:
                return self.last_frame
            time.sleep(0.1)
        self.screen_locked = True

        hwnd_dc = win32gui.GetWindowDC(self.parent_hwnd)
        mfc_dc = win32ui.CreateDCFromHandle(hwnd_dc)
        save_dc = mfc_dc.CreateCompatibleDC()

        bit_map = win32ui.CreateBitmap()
        bit_map.CreateCompatibleBitmap(mfc_dc, self.parent_width,
                                       self.parent_height)

        save_dc.SelectObject(bit_map)
        windll.user32.PrintWindow(self.parent_hwnd, save_dc.GetSafeHdc(), 1)

        bmp_info = bit_map.GetInfo()
        bmp_arr = bit_map.GetBitmapBits(True)

        win32gui.DeleteObject(bit_map.GetHandle())
        save_dc.DeleteDC()
        mfc_dc.DeleteDC()
        win32gui.ReleaseDC(self.parent_hwnd, hwnd_dc)

        self.screen_locked = False
        parent_img = Image.frombuffer(
            'RGB', (bmp_info['bmWidth'], bmp_info['bmHeight']), bmp_arr, 'raw',
            'BGRX', 0, 1)
        img = parent_img.crop((self.x1, self.y1, self.x2, self.y2))
        self.last_frame = img
        return img
Exemple #21
0
def get_screen(hwnd):
    global OS_WIN

    if OS_WIN:
        # Get bitmap data from win32
        wDC = win32gui.GetWindowDC(hwnd)
        dcObj = win32ui.CreateDCFromHandle(wDC)
        cDC = dcObj.CreateCompatibleDC()

        dataBitMap = win32ui.CreateBitmap()

        # Calculate dimensions
        l, t, r, b = win32gui.GetWindowRect(hwnd)
        h = b - t
        w = r - l

        # Create bitmap from data
        dataBitMap.CreateCompatibleBitmap(dcObj, w, h)
        cDC.SelectObject(dataBitMap)
        cDC.BitBlt((0, 0), (w, h), dcObj, (0, 0), win32con.SRCCOPY)

        # Convert to PIL
        bmpinfo = dataBitMap.GetInfo()
        bmpstr = dataBitMap.GetBitmapBits(True)
        im = Image.frombuffer('RGB', (bmpinfo['bmWidth'], bmpinfo['bmHeight']),
                              bmpstr, 'raw', 'BGRX', 0, 1)

        # Free Resources
        dcObj.DeleteDC()
        cDC.DeleteDC()
        win32gui.ReleaseDC(hwnd, wDC)
        win32gui.DeleteObject(dataBitMap.GetHandle())

    else:
        with mss.mss() as sct:
            sct_img = sct.grab(sct.monitors[1])
            im = Image.frombytes('RGB', sct_img.size, sct_img.rgb)

    return im