Python win32gui.GetWindowRect() Examples

The following are 30 code examples of win32gui.GetWindowRect(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module win32gui , or try the search function .
Example #1
Source File: Clicker.py    From roc with MIT License 15 votes vote down vote up
def find_window_movetop(cls):
        hwnd = win32gui.FindWindow(None, cls.processname)
        win32gui.ShowWindow(hwnd,5)
        win32gui.SetForegroundWindow(hwnd)
        rect = win32gui.GetWindowRect(hwnd)
        sleep(0.2)
        return rect 
Example #2
Source File: __init__.py    From EventGhost with GNU General Public License v2.0 6 votes vote down vote up
def GetWindowState(self):
        hWnd = Find_MPC()
        if not hWnd:
            return -1
        else:
            hWnd = hWnd[0]
        if not IsWindowVisible(hWnd):
            return 0
        state = GetWindowPlacement(hWnd)[1]
        border = GetWindowLong(hWnd, GWL_EXSTYLE) & WS_EX_WINDOWEDGE
        if border:
            return state
        rect = GetWindowRect(hWnd)
        mons = EnumDisplayMonitors()
        fullscreen = False
        for mon in mons:
            if rect == mon[2]:
                fullscreen = True
                break
        if fullscreen:
            return 4
        return state
#=============================================================================== 
Example #3
Source File: win32gui_dialog.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def OnInitDialog(self, hwnd, msg, wparam, lparam):
        self.hwnd = hwnd
        # centre the dialog
        desktop = win32gui.GetDesktopWindow()
        l,t,r,b = win32gui.GetWindowRect(self.hwnd)
        dt_l, dt_t, dt_r, dt_b = win32gui.GetWindowRect(desktop)
        centre_x, centre_y = win32gui.ClientToScreen( desktop, ( (dt_r-dt_l)//2, (dt_b-dt_t)//2) )
        win32gui.MoveWindow(hwnd, centre_x-(r//2), centre_y-(b//2), r-l, b-t, 0)
        self._SetupList()
        l,t,r,b = win32gui.GetClientRect(self.hwnd)
        self._DoSize(r-l,b-t, 1) 
Example #4
Source File: win32gui_dialog.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def _DoSize(self, cx, cy, repaint = 1):
        # right-justify the textbox.
        ctrl = win32gui.GetDlgItem(self.hwnd, IDC_SEARCHTEXT)
        l, t, r, b = win32gui.GetWindowRect(ctrl)
        l, t = win32gui.ScreenToClient(self.hwnd, (l,t) )
        r, b = win32gui.ScreenToClient(self.hwnd, (r,b) )
        win32gui.MoveWindow(ctrl, l, t, cx-l-5, b-t, repaint)
        # The button.
        ctrl = win32gui.GetDlgItem(self.hwnd, IDC_BUTTON_DISPLAY)
        l, t, r, b = win32gui.GetWindowRect(ctrl)
        l, t = win32gui.ScreenToClient(self.hwnd, (l,t) )
        r, b = win32gui.ScreenToClient(self.hwnd, (r,b) )
        list_y = b + 10
        w = r - l
        win32gui.MoveWindow(ctrl, cx - 5 - w, t, w, b-t, repaint)

        # The list control
        win32gui.MoveWindow(self.hwndList, 0, list_y, cx, cy-list_y, repaint)
        # The last column of the list control.
        new_width = cx - win32gui.SendMessage(self.hwndList, commctrl.LVM_GETCOLUMNWIDTH, 0)
        win32gui.SendMessage(self.hwndList, commctrl.LVM_SETCOLUMNWIDTH, 1, new_width) 
Example #5
Source File: win32rcparser_demo.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def OnInitDialog(self, hwnd, msg, wparam, lparam):
        self.hwnd = hwnd
        # centre the dialog
        desktop = win32gui.GetDesktopWindow()
        l,t,r,b = win32gui.GetWindowRect(self.hwnd)
        dt_l, dt_t, dt_r, dt_b = win32gui.GetWindowRect(desktop)
        centre_x, centre_y = win32gui.ClientToScreen( desktop, ( (dt_r-dt_l)//2, (dt_b-dt_t)//2) )
        win32gui.MoveWindow(hwnd, centre_x-(r//2), centre_y-(b//2), r-l, b-t, 0) 
Example #6
Source File: simpledialog.py    From eavatar-me with Apache License 2.0 6 votes vote down vote up
def OnInitDialog(self, hwnd, msg, wparam, lparam):
        self.hwnd = hwnd
        # centre the dialog
        desktop = win32gui.GetDesktopWindow()
        l, t, r, b = win32gui.GetWindowRect(self.hwnd)
        dt_l, dt_t, dt_r, dt_b = win32gui.GetWindowRect(desktop)
        centre_x, centre_y = win32gui.ClientToScreen(
            desktop,
            ((dt_r-dt_l)//2, (dt_b-dt_t)//2))
        win32gui.MoveWindow(hwnd, centre_x-(r//2),
                            centre_y-(b//2), r-l, b-t, 0)
        # self._SetupList()
        l, t, r, b = win32gui.GetClientRect(self.hwnd)
        self._DoSize(r-l, b-t, 1) 
Example #7
Source File: notice_dlg.py    From eavatar-me with Apache License 2.0 6 votes vote down vote up
def _DoSize(self, cx, cy, repaint=1):
        # right-justify the textbox.
        # ctrl = win32gui.GetDlgItem(self.hwnd, IDC_JOB_NAME)
        # win32gui.SetWindowText(ctrl, self.job_name)
        # l, t, r, b = win32gui.GetWindowRect(ctrl)
        # l, t = win32gui.ScreenToClient(self.hwnd, (l, t))
        # r, b = win32gui.ScreenToClient(self.hwnd, (r, b))
        # win32gui.MoveWindow(ctrl, l, t, cx-l-5, b-t, repaint)

        ctrl = win32gui.GetDlgItem(self.hwnd, IDC_SCRIPT)
        win32gui.SetFocus(ctrl)

        # The button.
        ctrl = win32gui.GetDlgItem(self.hwnd, IDC_BUTTON_SUBMIT)
        l, t, r, b = win32gui.GetWindowRect(ctrl)
        l, t = win32gui.ScreenToClient(self.hwnd, (l, t))
        r, b = win32gui.ScreenToClient(self.hwnd, (r, b))
        w = r - l
        win32gui.MoveWindow(ctrl, cx - 5 - w, t, w, b-t, repaint) 
Example #8
Source File: notice_dlg.py    From eavatar-me with Apache License 2.0 6 votes vote down vote up
def OnInitDialog(self, hwnd, msg, wparam, lparam):
        self.hwnd = hwnd
        # centre the dialog
        desktop = win32gui.GetDesktopWindow()
        l, t, r, b = win32gui.GetWindowRect(self.hwnd)
        dt_l, dt_t, dt_r, dt_b = win32gui.GetWindowRect(desktop)
        centre_x, centre_y = win32gui.ClientToScreen(desktop,
                                                     ((dt_r - dt_l)//2,
                                                      (dt_b - dt_t)//2))
        win32gui.MoveWindow(hwnd, centre_x-(r//2),
                            centre_y-(b//2), r-l, b-t, 0)
        # self._SetupList()
        l, t, r, b = win32gui.GetClientRect(self.hwnd)
        self._DoSize(r-l, b-t, 1) 
Example #9
Source File: console.py    From eavatar-me with Apache License 2.0 6 votes vote down vote up
def _DoSize(self, cx, cy, repaint=1):
        # right-justify the textbox.
        # ctrl = win32gui.GetDlgItem(self.hwnd, IDC_JOB_NAME)
        # win32gui.SetWindowText(ctrl, self.job_name)
        # l, t, r, b = win32gui.GetWindowRect(ctrl)
        # l, t = win32gui.ScreenToClient(self.hwnd, (l, t))
        # r, b = win32gui.ScreenToClient(self.hwnd, (r, b))
        # win32gui.MoveWindow(ctrl, l, t, cx-l-5, b-t, repaint)

        ctrl = win32gui.GetDlgItem(self.hwnd, IDC_SCRIPT)
        win32gui.SetFocus(ctrl)

        # The button.
        ctrl = win32gui.GetDlgItem(self.hwnd, IDC_BUTTON_SUBMIT)
        l, t, r, b = win32gui.GetWindowRect(ctrl)
        l, t = win32gui.ScreenToClient(self.hwnd, (l, t))
        r, b = win32gui.ScreenToClient(self.hwnd, (r, b))
        w = r - l
        win32gui.MoveWindow(ctrl, cx - 5 - w, t, w, b - t, repaint) 
Example #10
Source File: console.py    From eavatar-me with Apache License 2.0 6 votes vote down vote up
def OnInitDialog(self, hwnd, msg, wparam, lparam):
        self.hwnd = hwnd
        # centre the dialog
        desktop = win32gui.GetDesktopWindow()
        l, t, r, b = win32gui.GetWindowRect(self.hwnd)
        dt_l, dt_t, dt_r, dt_b = win32gui.GetWindowRect(desktop)
        centre_x, centre_y = win32gui.ClientToScreen(desktop, (
            (dt_r - dt_l) // 2, (dt_b - dt_t) // 2))
        win32gui.MoveWindow(hwnd, centre_x - (r // 2), centre_y - (b // 2),
                            r - l, b - t, 0)
        # self._SetupList()
        l, t, r, b = win32gui.GetClientRect(self.hwnd)
        self._DoSize(r - l, b - t, 1) 
Example #11
Source File: windows.py    From ATX with Apache License 2.0 6 votes vote down vote up
def __init_rect_size(self):
        hwnd = self.hwnd
        left, top, right, bottom = win32gui.GetWindowRect(hwnd)
        if self.exclude_border:
            _left, _top, _right, _bottom = win32gui.GetClientRect(hwnd)
            left, top = win32gui.ClientToScreen(hwnd, (_left, _top))
            right, bottom = win32gui.ClientToScreen(hwnd, (_right, _bottom))
        self._rect = Rect(left, top, right, bottom)
        self._size = Size(right-left, bottom-top) 
Example #12
Source File: game_ctl.py    From onmyoji_bot with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, hwnd, quit_game_enable=1):
        '''
        初始化
            :param hwnd: 需要绑定的窗口句柄
            :param quit_game_enable: 程序死掉时是否退出游戏。True为是,False为否
        '''
        self.run = True
        self.hwnd = hwnd
        self.quit_game_enable = quit_game_enable
        self.debug_enable = False
        l1, t1, r1, b1 = win32gui.GetWindowRect(self.hwnd)
        #print(l1,t1, r1,b1)
        l2, t2, r2, b2 = win32gui.GetClientRect(self.hwnd)
        # print(l2,t2,r2,b2)
        self._client_h = b2 - t2
        self._client_w = r2 - l2
        self._border_l = ((r1 - l1) - (r2 - l2)) // 2
        self._border_t = ((b1 - t1) - (b2 - t2)) - self._border_l
        conf = configparser.ConfigParser()
        conf.read('conf.ini')
        self.client = conf.getint('DEFAULT', 'client')
        if self.client == 1:
            os.system('adb connect 127.0.0.1:7555')
            os.system('adb devices') 
Example #13
Source File: windows.py    From ATX with Apache License 2.0 6 votes vote down vote up
def rect(self):
        hwnd = self.hwnd
        if not self.exclude_border:
            left, top, right, bottom = win32gui.GetWindowRect(hwnd)
        else:
            _left, _top, _right, _bottom = win32gui.GetClientRect(hwnd)
            left, top = win32gui.ClientToScreen(hwnd, (_left, _top))
            right, bottom = win32gui.ClientToScreen(hwnd, (_right, _bottom))
        return Rect(left, top, right, bottom) 
Example #14
Source File: FollowWindow.py    From PyQt with GNU General Public License v3.0 5 votes vote down vote up
def checkWindow(self):
        # 查找
        hwnd = win32gui.FindWindow('Notepad', None)
        if self.tmpHwnd and not hwnd:
            # 表示记事本关闭了
            self.checkTimer.stop()
            self.close()  # 关闭自己
            return
        if not hwnd:
            return
        self.tmpHwnd = hwnd
        # 获取位置
        rect = win32gui.GetWindowRect(hwnd)
        print(rect)
        self.move(rect[2], rect[1]) 
Example #15
Source File: winapi.py    From gui-o-matic with GNU Lesser General Public License v3.0 5 votes vote down vote up
def get_size( self ):
        return win32gui.GetWindowRect( self.window_handle ) 
Example #16
Source File: ProbeWindow.py    From PyQt with GNU General Public License v3.0 5 votes vote down vote up
def mouseMoveEvent(self, event):
        super(Label, self).mouseMoveEvent(event)
        # 得到鼠标在屏幕中的位置
        pos = self.mapToGlobal(event.pos())
        hwnd = win32gui.WindowFromPoint((pos.x(), pos.y()))
        self.frameWidget.setRect(*win32gui.GetWindowRect(hwnd))
        # 截图
        screen = QApplication.primaryScreen()
        if screen is not None:
            image = screen.grabWindow(0,
                                      pos.x() - 60, pos.y() - 60, 120, 120)
            if not image.isNull():
                self.setPixmap(image.scaled(240, 240)) 
Example #17
Source File: winguiauto.py    From pyAutoTrading with GNU General Public License v2.0 5 votes vote down vote up
def clickWindow(hwnd, offset):
    left, top, right, bottom = win32gui.GetWindowRect(hwnd)
    # print('left, top, right, bottom', left, top, right, bottom)
    win32api.SetCursorPos([left + offset, (bottom - top) // 2 + top])
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0)
    time.sleep(0.2)
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, 0, 0, 0, 0)
    time.sleep(0.2) 
Example #18
Source File: steam.py    From Yugioh-bot with MIT License 5 votes vote down vote up
def take_png_screenshot(self):
        if not self.win_handle:
            raise Exception("Win handle is not valid for Steam")
        # Crops the image from the desktop
        left, top, right, bottom = win32gui.GetWindowRect(self.win_handle)
        width = right - left
        height = bottom - top
        hwnd_dc = win32gui.GetWindowDC(self.win_handle)
        # Get a bitmap
        mfc_dc = win32ui.CreateDCFromHandle(hwnd_dc)
        save_dc = mfc_dc.CreateCompatibleDC()
        save_bit_map = win32ui.CreateBitmap()
        save_bit_map.CreateCompatibleBitmap(mfc_dc, width, height)
        save_dc.SelectObject(save_bit_map)
        result = windll.user32.PrintWindow(self.win_handle, save_dc.GetSafeHdc(), 0x00000002)
        if result != 1:
            raise Exception("Failed to Steam screen")
        bmp_info = save_bit_map.GetInfo()
        bmp_raw = save_bit_map.GetBitmapBits(False)
        img = np.array(bmp_raw, np.uint8).reshape(bmp_info['bmHeight'], bmp_info['bmWidth'], 4)
        # Clean Up
        win32gui.DeleteObject(save_bit_map.GetHandle())
        save_dc.DeleteDC()
        mfc_dc.DeleteDC()
        win32gui.ReleaseDC(self.win_handle, hwnd_dc)
        img_str = cv2.imencode('.jpg', img)[1].tostring()
        return img_str 
Example #19
Source File: window.py    From NGU-scripts with GNU Lesser General Public License v3.0 5 votes vote down vote up
def winRect(window_id :int) -> Tuple[int, int, int, int]:
        """Returns the coordinates of the window"""
        return win32gui.GetWindowRect(window_id) 
Example #20
Source File: Demo_Save_Any_Window_As_Image.py    From PySimpleGUI with GNU Lesser General Public License v3.0 5 votes vote down vote up
def save_win(filename=None, title=None):
    """
    Saves a window with the title provided as a file using the provided filename.
    If one of them is missing, then a window is created and the information collected

    :param filename:
    :param title:
    :return:
    """
    C = 7   # pixels to crop
    if filename is None or title is None:
        layout = [[sg.T('Choose window to save', font='Any 18')],
                  [sg.T('The extension you choose for filename will determine the image format')],
                  [sg.T('Window Title:', size=(12,1)), sg.I(title if title is not None else '', key='-T-')],
                  [sg.T('Filename:', size=(12,1)), sg.I(filename if filename is not None else '', key='-F-')],
                  [sg.Button('Ok', bind_return_key=True), sg.Button('Cancel')]]
        event, values = sg.Window('Choose Win Title and Filename',layout).read(close=True)
        if event != 'Ok':   # if cancelled or closed the window
            print('Cancelling the save')
            return
        filename, title = values['-F-'], values['-T-']
    try:
        fceuxHWND = win32gui.FindWindow(None, title)
        rect = win32gui.GetWindowRect(fceuxHWND)
        rect_cropped = (rect[0]+C, rect[1], rect[2]-C, rect[3]-C)
        frame = np.array(ImageGrab.grab(bbox=rect_cropped), dtype=np.uint8)
        frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        cv2.imwrite(filename, frame)
        sg.popup('Wrote image to file:',filename)
    except Exception as e:
        sg.popup('Error trying to save screenshot file', e) 
Example #21
Source File: Demo_Save_Windows_As_Images.py    From PySimpleGUI with GNU Lesser General Public License v3.0 5 votes vote down vote up
def save_win(filename=None, title=None, crop=True):
    """
    Saves a window with the title provided as a file using the provided filename.
    If one of them is missing, then a window is created and the information collected

    :param filename:
    :param title:
    :return:
    """
    C = 7 if crop else 0  # pixels to crop
    if filename is None or title is None:
        layout = [[sg.T('Choose window to save', font='Any 18')],
                  [sg.T('The extension you choose for filename will determine the image format')],
                  [sg.T('Window Title:', size=(12, 1)), sg.I(title if title is not None else '', key='-T-')],
                  [sg.T('Filename:', size=(12, 1)), sg.I(filename if filename is not None else '', key='-F-')],
                  [sg.Button('Ok', bind_return_key=True), sg.Button('Cancel')]]
        event, values = sg.Window('Choose Win Title and Filename', layout).read(close=True)
        if event != 'Ok':  # if cancelled or closed the window
            print('Cancelling the save')
            return
        filename, title = values['-F-'], values['-T-']
    try:
        fceuxHWND = win32gui.FindWindow(None, title)
        rect = win32gui.GetWindowRect(fceuxHWND)
        rect_cropped = (rect[0] + C, rect[1], rect[2] - C, rect[3] - C)
        frame = np.array(ImageGrab.grab(bbox=rect_cropped), dtype=np.uint8)
        frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        cv2.imwrite(filename, frame)
        sg.cprint('Wrote image to file:', filename)
    except Exception as e:
        sg.popup('Error trying to save screenshot file', e, keep_on_top=True) 
Example #22
Source File: main.py    From MouseTracks with GNU General Public License v3.0 5 votes vote down vote up
def rect(self):
        """Get the coordinates of a window."""
        try:
            return win32gui.GetWindowRect(self.hwnd)
        except win32api.error:
            return (0, 0, 0, 0) 
Example #23
Source File: run.py    From Auto-Lianliankan with Apache License 2.0 5 votes vote down vote up
def getGameWindowPosition():
    # FindWindow(lpClassName=None, lpWindowName=None)  窗口类名 窗口标题名
    window = win32gui.FindWindow(None,WINDOW_TITLE)
    # 没有定位到游戏窗体
    while not window:
        print('定位游戏窗体失败,5秒后重试...')
        time.sleep(5)
        window = win32gui.FindWindow(None,WINDOW_TITLE)
    # 定位到游戏窗体
    win32gui.SetForegroundWindow(window) # 将窗体顶置
    pos = win32gui.GetWindowRect(window)
    print("定位到游戏窗体:" + str(pos))
    return (pos[0],pos[1])

# 获取一张完整的屏幕截图 
Example #24
Source File: functions.py    From bot with MIT License 5 votes vote down vote up
def set_window_coordinates(hwnd, window_info):
    if win32gui.IsWindowVisible(hwnd):
        if WINDOW_SUBSTRING in win32gui.GetWindowText(hwnd):
            rect = win32gui.GetWindowRect(hwnd)
            x = rect[0]
            y = rect[1]
            w = rect[2] - x
            h = rect[3] - y
            window_info['x'] = x
            window_info['y'] = y
            window_info['width'] = w
            window_info['height'] = h
            window_info['name'] = win32gui.GetWindowText(hwnd)
            win32gui.SetForegroundWindow(hwnd) 
Example #25
Source File: winguiauto.py    From pyautotrade_tdx with GNU General Public License v2.0 5 votes vote down vote up
def clickMenuButton(hwnd, offset):
    left, top, right, bottom = win32gui.GetWindowRect(hwnd)
    win32api.SetCursorPos([left + offset, (bottom - top) // 2 + top])
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0)
    time.sleep(0.1)
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, 0, 0, 0, 0)
    time.sleep(0.3) 
Example #26
Source File: win_ide.py    From Airtest with Apache License 2.0 5 votes vote down vote up
def get_rect(self):
        """
        Get rectangle of app or desktop resolution

        Returns:
            RECT(left, top, right, bottom)

        """
        if self.handle:
            left, top, right, bottom = win32gui.GetWindowRect(self.handle)
            return RECT(left, top, right, bottom)
        else:
            desktop = win32gui.GetDesktopWindow()
            left, top, right, bottom = win32gui.GetWindowRect(desktop)
            return RECT(left, top, right, bottom) 
Example #27
Source File: Screenshot.py    From roc with MIT License 4 votes vote down vote up
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") 
Example #28
Source File: screen.py    From Airtest with Apache License 2.0 4 votes vote down vote up
def screenshot(filename, hwnd=None):
    """
    Take the screenshot of Windows app

    Args:
        filename: file name where to store the screenshot
        hwnd:

    Returns:
        bitmap screenshot file

    """
    # import ctypes
    # user32 = ctypes.windll.user32
    # user32.SetProcessDPIAware()

    if hwnd is None:
        """all screens"""
        hwnd = win32gui.GetDesktopWindow()
        # get complete virtual screen including all monitors
        w = win32api.GetSystemMetrics(SM_CXVIRTUALSCREEN)
        h = win32api.GetSystemMetrics(SM_CYVIRTUALSCREEN)
        x = win32api.GetSystemMetrics(SM_XVIRTUALSCREEN)
        y = win32api.GetSystemMetrics(SM_YVIRTUALSCREEN)
    else:
        """window"""
        rect = win32gui.GetWindowRect(hwnd)
        w = abs(rect[2] - rect[0])
        h = abs(rect[3] - rect[1])
        x, y = 0, 0
    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, (x, y), win32con.SRCCOPY)
    # saveBitMap.SaveBitmapFile(saveDC, filename)
    bmpinfo = saveBitMap.GetInfo()
    bmpstr = saveBitMap.GetBitmapBits(True)
    pil_image = Image.frombuffer(
        'RGB',
        (bmpinfo['bmWidth'], bmpinfo['bmHeight']),
        bmpstr, 'raw', 'BGRX', 0, 1)
    cv2_image = pil_2_cv2(pil_image)

    mfcDC.DeleteDC()
    saveDC.DeleteDC()
    win32gui.ReleaseDC(hwnd, hwndDC)
    win32gui.DeleteObject(saveBitMap.GetHandle())
    return cv2_image 
Example #29
Source File: window.py    From Automatic-minesweeping with MIT License 4 votes vote down vote up
def __init__(self):
        self.hwnd = FindWindow(None, "扫雷")  # 获取扫雷游戏窗口的句柄
        assert self.hwnd, "请先打开扫雷,再运行该脚本程序"
        SendMessage(self.hwnd, WM_SYSCOMMAND, SC_RESTORE, 0)  # 还原最小化
        SetForegroundWindow(self.hwnd)  # 窗口置顶

        self.pixel_size = 16  # 每个格子的大小固定,为16个像素
        self.left, self.top, self.right, self.bottom = GetWindowRect(self.hwnd)  # 获取窗口坐标
        self.rank = None  # 扫雷游戏的等级,分为:高级、中级、初级,不包含自定义模式
        self.max_mines = 0  # 扫雷游戏的所有雷的数目

        # 去除窗口边框,只保留所有格子
        self.left = self.left + 15  # 左边框15个像素宽
        self.right = self.right - 11  # 右边框11个像素宽
        self.bottom = self.bottom - 11  # 下边框11个像素宽
        self.top = self.top + 101  # 尚边框101个像素宽

        # 获得游戏横向和纵向的格子数目
        self.height = int((self.bottom - self.top) / self.pixel_size)  # 扫雷游戏的纵向格子数目
        assert self.height in [16, 16, 9]
        self.length = int((self.right - self.left) / self.pixel_size)  # 扫雷游戏的横向格子数目
        assert self.length in [30, 16, 9]

        # 获取游戏难度级别
        self.get_rank()
        self.get_max_mines() 
Example #30
Source File: ScreenViewer.py    From poeai with MIT License 4 votes vote down vote up
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]