Python win32gui.GetWindowRect() Examples

The following are code examples for showing how to use win32gui.GetWindowRect(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: BomberCrewBot   Author: ajchili   File: takeoffmanager.py    GNU General Public License v3.0 8 votes vote down vote up
def takeoff():
    pyautogui.press('1')
    try:
        hwnd = win32gui.FindWindow("UnityWndClass", None)
        left, top, right, bottom = win32gui.GetWindowRect(hwnd)
    except pywintypes.error:
        print("Bomber Crew Window Not Found!")
        return False

    width = right - left
    height = bottom - top
    x = int(left + width / 2)
    y = int(top + height * 0.8)
    win32api.SetCursorPos((x, y))
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, x, y, 0, 0)
    Timer(0.01, win32api.mouse_event, [win32con.MOUSEEVENTF_LEFTUP, x, y, 0, 0, ]).start()
    return True 
Example 2
Project: ironpython2   Author: IronLanguages   File: win32gui_dialog.py    Apache License 2.0 7 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 3
Project: MillionHeroHybridAssist   Author: leyuwei   File: airplayscr.py    MIT License 7 votes vote down vote up
def window_capture(filename):
    main_app = "" # Airplayer
    hwnd = win32gui.FindWindow("CHWindow",main_app)
    hwnd1 = win32gui.FindWindowEx(hwnd,0,"CHWindow",None)
    if hwnd1==0:
        print("获取iOS截图失败,请确认投屏软件是否存在任务栏中,设备连接是否正常!")
    # 根据窗口句柄获取窗口的设备上下文DC(Divice Context)
    hwndDC = win32gui.GetWindowDC(hwnd1)
    # 根据窗口的DC获取mfcDC
    mfcDC = win32ui.CreateDCFromHandle(hwndDC)
    # mfcDC创建可兼容的DC
    saveDC = mfcDC.CreateCompatibleDC()
    # 创建bigmap准备保存图片
    saveBitMap = win32ui.CreateBitmap()
    # 获取窗口大小
    _left,_top,_right,_bottom = win32gui.GetWindowRect(hwnd1)
    w = _right-_left
    h = _bottom-_top
    # 为bitmap开辟空间
    saveBitMap.CreateCompatibleBitmap(mfcDC, w, h)
    # 高度saveDC,将截图保存到saveBitmap中
    saveDC.SelectObject(saveBitMap)
    # 截取从左上角(0,0)长宽为(w,h)的图片
    saveDC.BitBlt((0, 0), (w, h), mfcDC, (0, 0), win32con.SRCCOPY)
    saveBitMap.SaveBitmapFile(saveDC, filename) 
Example 4
Project: KivyOnTop   Author: JakubBlaha   File: __init__.py    MIT License 7 votes vote down vote up
def set_not_always_on_top(title: str):
    '''
    Sets the HWND_NOTOPMOST flag for the current Kivy Window.
    '''

    global hwnd

    if not 'hwnd' in globals():
        find_hwnd(title)

    rect = win32gui.GetWindowRect(hwnd)
    x = rect[0]
    y = rect[1]
    w = rect[2] - x
    h = rect[3] - y

    win32gui.SetWindowPos(hwnd, win32con.HWND_NOTOPMOST, x, y, w, h, 0) 
Example 5
Project: open-recipe   Author: dspray95   File: win32gui_dialog.py    The Unlicense 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 6
Project: BomberCrewBot   Author: ajchili   File: grabwindow.py    GNU General Public License v3.0 6 votes vote down vote up
def grab_window():
    global isRunning

    while isRunning:
        # Obtain Bomber Crew window size
        try:
            hwnd = win32gui.FindWindow("UnityWndClass", None)
            left, top, right, bottom = win32gui.GetWindowRect(hwnd)
        except pywintypes.error:
            print("Bomber Crew Window Not Found!")
            time.sleep(5)
        else:
            width = right - left
            height = bottom - top
            game_window = {'top': top, 'left': left, 'width': width, 'height': height}

            foreground_window_name = win32gui.GetWindowText(win32gui.GetForegroundWindow())

            if foreground_window_name == "Bomber Crew":
                game_capture = numpy.array(mss().grab(game_window))
                core.run(game_capture, width, height)
                cv2.waitKey(1)
            else:
                break 
Example 7
Project: spotify-scraper   Author: naschorr   File: spotify_scraper.py    MIT License 6 votes vote down vote up
def captureAlbumArt(self):
		while(self.windowHandle != GetForegroundWindow()):
			SetForegroundWindow(self.windowHandle)
			time.sleep(WAIT_TIME)	## Give Spotify a moment to come to the foreground
		ShowWindow(self.windowHandle, SW_SHOWMAXIMIZED)
		time.sleep(WAIT_TIME)	## Give Spotify a second to become maximized

		## Get the edges of the window
		left, top, right, bottom = GetWindowRect(self.windowHandle)
		left += self.artOffsets[0]
		bottom -= self.artOffsets[1]
		## Get the album art's location from those edges and user specified offsets.
		region = (left, bottom - self.artSideLength, left + self.artSideLength, bottom)
		return pyscreenshot.grab(bbox=region, childprocess=False) 
Example 8
Project: SasSubmit   Author: sjiangDA   File: helper.py    MIT License 6 votes vote down vote up
def activate(self, with_mouse=False, with_alt=True, x_w=0.5, y_w=0.5):
		rect = win32gui.GetWindowRect(self.hwnd)
		newx = int(x_w*rect[0]+(1-x_w)*rect[2])
		newy = int(y_w*rect[1]+(1-y_w)*rect[3])
		if newx + newy == 0:
			raise ValueError("Window cannot be found!")
		try:
			shell = win32com.client.Dispatch("WScript.Shell")
			if with_alt:
				shell.SendKeys('%')
			if win32gui.IsIconic(self.hwnd):
				win32gui.ShowWindow(self.hwnd, 9)
			win32gui.SetForegroundWindow(self.hwnd)
		except Exception as e:
			raise ValueError("Activate window failed!")

		if with_mouse:
			move_mouse_to(newx,newy) 
Example 9
Project: pytrade   Author: allisnone   File: easytrader_tdx_api.py    GNU General Public License v2.0 6 votes vote down vote up
def _click_rect(self,hwnd,x_offset=0,y_offset=0,x_0='left',y_0='top',foreground=True):
        if hwnd:
            try:
                if foreground:
                    self._set_foreground_window(hwnd)
            except:
                pass
        else:
            return
        rect = win32gui.GetWindowRect(hwnd)  #(left,top,right,bottom)
        if x_0=='left':
            x = rect[0]
        elif x_0=='right':
            x = rect[2]
        else:
            return
        if y_0=='top':
            y = rect[1]
        elif y_0=='bottom':
            y = rect[3]
        else:
            return
        self._mouse_click(x + x_offset, y+y_offset)
        time.sleep(0.5)
        return 
Example 10
Project: pytrade   Author: allisnone   File: easytrader_tdx_api.py    GNU General Public License v2.0 6 votes vote down vote up
def _click_trade_only(self):
        #input_hwnd = win32gui.GetDlgItem(self.login_hwnd, 0x016E)
        trade_hwnd_id = 0x016C
        #rect = win32gui.GetWindowRect(input_hwnd)
        if self.type=='trade_only':
            trade_hwnd_id = 0x016E
            print('选择独立交易')
        elif self.type=='quote_only':
            trade_hwnd_id = 0x016D
            print('选择独立行情')
        elif self.type=='trade_and_quote':
            print('选择行情+交易')
        else:
            print('选择行情+交易')
            pass
        try:
            self._set_foreground_window(self.login_hwnd)
        except:
            pass
        input_hwnd = win32gui.GetDlgItem(self.login_hwnd, trade_hwnd_id)
        rect = win32gui.GetWindowRect(input_hwnd)
        self._mouse_click(rect[0] + 20, rect[1]+10) 
Example 11
Project: arkScript   Author: akbchris   File: win32gui_dialog.py    MIT License 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 12
Project: onmyoji_bot   Author: AcademicDog   File: game_ctl.py    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
        #user32 = ctypes.windll.user32
        #user32.SetProcessDPIAware()
        l1,t1,r1,b1 = win32gui.GetWindowRect(self.hwnd)
        l2,t2,r2,b2 = win32gui.GetClientRect(self.hwnd)
        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 
Example 13
Project: eavatar-me   Author: eavatar   File: console.py    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 14
Project: eavatar-me   Author: eavatar   File: notice_dlg.py    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 15
Project: NGU-scripts   Author: kujan   File: window.py    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 16
Project: NGU-scripts   Author: kujan   File: inputs.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def get_bitmap() -> image:
        """Get and return a bitmap of the Window."""
        left, top, right, bot = win32gui.GetWindowRect(Window.id)
        w = right - left
        h = bot - top
        hwnd_dc = win32gui.GetWindowDC(Window.id)
        mfc_dc = win32ui.CreateDCFromHandle(hwnd_dc)
        save_dc = mfc_dc.CreateCompatibleDC()
        save_bitmap = win32ui.CreateBitmap()
        save_bitmap.CreateCompatibleBitmap(mfc_dc, w, h)
        save_dc.SelectObject(save_bitmap)
        windll.user32.PrintWindow(Window.id, save_dc.GetSafeHdc(), 0)
        bmpinfo = save_bitmap.GetInfo()
        bmpstr = save_bitmap.GetBitmapBits(True)

        # This creates an Image object from Pillow
        bmp = image.frombuffer('RGB',
                               (bmpinfo['bmWidth'],
                                bmpinfo['bmHeight']),
                               bmpstr, 'raw', 'BGRX', 0, 1)

        win32gui.DeleteObject(save_bitmap.GetHandle())
        save_dc.DeleteDC()
        mfc_dc.DeleteDC()
        win32gui.ReleaseDC(Window.id, hwnd_dc)
        # bmp.save("asdf.png")
        return bmp 
Example 17
Project: poeai   Author: nicholastoddsmith   File: ScreenViewer.py    MIT License 5 votes vote down vote up
def GetHWND(self, wname = None):
        '''
        Gets handle of window to view
        wname:         Title of window to find
        Return:        True on success; False on failure
        '''
        if wname is None:
            self.hwnd = win32gui.GetDesktopWindow()
        else:
            self.hwnd = win32gui.FindWindow(None, wname)    
        if self.hwnd == 0:
            self.hwnd = None
            return False
        self.l, self.t, self.r, self.b = win32gui.GetWindowRect(self.hwnd)
        return True 
Example 18
Project: poeai   Author: nicholastoddsmith   File: ScreenViewer.py    MIT License 5 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] 
Example 19
Project: gjqt-script   Author: 1178615156   File: windows_winio.py    GNU General Public License v3.0 5 votes vote down vote up
def screen_shot(self):
        game_rect = win32gui.GetWindowRect(self.hwnd)
        src_image = ImageGrab.grab(game_rect)
        return src_image 
Example 20
Project: Advanced-Action-Scheduler   Author: swprojects   File: windowmanager.py    GNU General Public License v2.0 5 votes vote down vote up
def GetWindowRect(handle):
    x1, y1, x2, y2 = win32gui.GetWindowRect(handle)
    # print([x1, y1, x2, y2])
    return [x1, y1, x2, y2] 
Example 21
Project: Advanced-Action-Scheduler   Author: swprojects   File: windowmanager.py    GNU General Public License v2.0 5 votes vote down vote up
def MoveWindow(handle, x1, y1, w, h):

    if w is None:  # size not defined
        tmpX1, tmpY1, tmpX2, tmpY2 = win32gui.GetWindowRect(handle)
        w = tmpX2 - tmpX1
        h = tmpY2 - tmpY1

    win32gui.MoveWindow(handle, x1, y1, w, h, True) 
Example 22
Project: Advanced-Action-Scheduler   Author: swprojects   File: windowmanager.py    GNU General Public License v2.0 5 votes vote down vote up
def SetWindowSize(handle, w, h):
    x1, y1, _, _ = win32gui.GetWindowRect(handle)
    win32gui.MoveWindow(handle, x1, y1, w, h, True) 
Example 23
Project: ironpython2   Author: IronLanguages   File: win32gui_dialog.py    Apache License 2.0 5 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 24
Project: ironpython2   Author: IronLanguages   File: win32rcparser_demo.py    Apache License 2.0 5 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 25
Project: open-recipe   Author: dspray95   File: win32gui_dialog.py    The Unlicense 5 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 26
Project: open-recipe   Author: dspray95   File: win32rcparser_demo.py    The Unlicense 5 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 27
Project: Automatic-minesweeping   Author: buaazyc   File: window.py    MIT License 5 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 28
Project: Airtest   Author: AirtestProject   File: win_ide.py    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 29
Project: touhou10-dqn   Author: actumn   File: process.py    MIT License 5 votes vote down vote up
def image_grab(hwnd, bbox):
    window_bbox = win32gui.GetWindowRect(hwnd)
    bbox = tuple(map(operator.add, bbox, window_bbox))
    return ImageGrab.grab(bbox) 
Example 30
Project: AutoOnmyoji   Author: sup817ch   File: game_ctl.py    MIT License 5 votes vote down vote up
def window_full_shot(self,file_name=None):
        """
        窗口截图
            :param file_name=None: 截图文件的保存名称
            :return: file_name为空则返回RGB数据
        """
        try:
            l, t, r, b = win32gui.GetWindowRect(self.hwnd)
            #39和16为Window与Client高和宽的差值
            h = b - t - 39
            w = r - l - 16
            hwindc = win32gui.GetWindowDC(self.hwnd)
            srcdc = win32ui.CreateDCFromHandle(hwindc)
            memdc = srcdc.CreateCompatibleDC()
            bmp = win32ui.CreateBitmap()
            bmp.CreateCompatibleBitmap(srcdc, w, h)
            memdc.SelectObject(bmp)
            memdc.BitBlt((0, 0), (w, h), srcdc, (8, 31), win32con.SRCCOPY)
            if file_name!=None:
                bmp.SaveBitmapFile(memdc,file_name)
                srcdc.DeleteDC()
                memdc.DeleteDC()
                win32gui.ReleaseDC(self.hwnd, hwindc)
                win32gui.DeleteObject(bmp.GetHandle())
                return
            else:
                signedIntsArray = bmp.GetBitmapBits(True)
                img = np.fromstring(signedIntsArray, dtype='uint8')
                img.shape = (h, w, 4)
                srcdc.DeleteDC()
                memdc.DeleteDC()
                win32gui.ReleaseDC(self.hwnd, hwindc)
                win32gui.DeleteObject(bmp.GetHandle())
                return cv2.cvtColor(img, cv2.COLOR_BGRA2RGB)
        except:
            pass 
Example 31
Project: bLyrics   Author: TheRealBanana   File: options_dialog_functions.py    GNU General Public License v2.0 5 votes vote down vote up
def forceDialogOnTop(self, dialogTitle):
        #Kind of a nasty hack here. The QColorDialog seems to be impossible to open on top of all other windows.
        #So we have to manually set the window position using win32gui and win32con
        if self.AOT is True:
            cpHandle = win32gui.FindWindow(None, dialogTitle)
            cpPos = win32gui.GetWindowRect(cpHandle)
            win32gui.SetWindowPos(cpHandle, win32con.HWND_TOPMOST, cpPos[0], cpPos[1], int(cpPos[2]-cpPos[0]), int(cpPos[3]-cpPos[1]), 0)
        #Kill the timer
        self.timer.stop() 
Example 32
Project: foto2vam   Author: ChrisTopherTa54321   File: window.py    GNU General Public License v3.0 5 votes vote down vote up
def _getVamRect(self):
        return win32gui.GetWindowRect(self._getVamHndl()) 
Example 33
Project: AutoSplit64   Author: Kainev   File: capture_window.py    GNU General Public License v3.0 5 votes vote down vote up
def capture(hwnd):
    """
    https://stackoverflow.com/a/24352388
    """
    left, top, right, bot = win32gui.GetWindowRect(hwnd)
    w = right - left
    h = bot - top


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

    save_bitmap = win32ui.CreateBitmap()
    save_bitmap.CreateCompatibleBitmap(mfc_dc, w, h)

    save_dc.SelectObject(save_bitmap)

    result = windll.user32.PrintWindow(hwnd, save_dc.GetSafeHdc(), 0)

    bmp_info = save_bitmap.GetInfo()
    bmp_str = save_bitmap.GetBitmapBits(True)

    image = np.fromstring(bmp_str, np.uint8).reshape(bmp_info['bmHeight'], bmp_info['bmWidth'], 4)[:,:,:3]

    win32gui.DeleteObject(save_bitmap.GetHandle())
    save_dc.DeleteDC()
    mfc_dc.DeleteDC()
    win32gui.ReleaseDC(hwnd, hwnd_dc)

    return image 
Example 34
Project: AutoSplit64   Author: Kainev   File: capture_window.py    GNU General Public License v3.0 5 votes vote down vote up
def get_capture_size(hwnd):
    left, top, right, bot = win32gui.GetWindowRect(hwnd)

    return [right - left, bot - top] 
Example 35
Project: GirlsFrontline-Assistant   Author: tripack45   File: device.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, name:str, scale=1.25):
        self.scale = scale

        logger = logging.getLogger(__name__)
        logger.info('id = %x, Opening Window of name :"%s"' % (id(self), name))

        self.__hwnd = win32gui.FindWindow(None, name)

        if self.__hwnd == 0:
            errmsg = 'Window hwnd not acquired, possible window not found'
            logger.error(errmsg)
            raise RuntimeError(errmsg)

        logger.debug("Window hWnd = %d" % self.__hwnd)

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

        # err = win32api.GetLastError()

        logger.debug("left, top, right, bot = %d, %d, %d, %d"
                     % (left, top, right, bot))

        self.__w = int(self.scale * (right - left))
        self.__h = int(self.scale * (bot - top))

        logger.debug("width = %d, height = %d" % (self.__w, self.__h))

        self.__hwndDC = win32gui.GetWindowDC(self.__hwnd)
        self.__mfcDC = win32ui.CreateDCFromHandle(self.__hwndDC)
        self.__saveDC = self.__mfcDC.CreateCompatibleDC()
        pass 
Example 36
Project: pyautotrade_tdx   Author: ynzheng   File: winguiauto.py    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 37
Project: SasSubmit   Author: sjiangDA   File: studio.py    MIT License 5 votes vote down vote up
def submit(self, instance, root_path):
    flags, hcursor, (x,y) = win32gui.GetCursorInfo()
    self.update_session_info()
    self.submit_to_broswer()
    move_mouse_to(x,y,with_click=False)

# SingleHwnd(19860206).activate()
# time.sleep(1)
# SingleHwnd(win32gui.GetForegroundWindow()).get_title()
# rect = win32gui.GetWindowRect(19860206) 
Example 38
Project: pytrade   Author: allisnone   File: easytrader_tdx_api.py    GNU General Public License v2.0 5 votes vote down vote up
def _click_download_data(self):
        """
        if self.tdx_menu_system_hwnd:
            try:
                self._set_foreground_window(self.tdx_menu_system_hwnd)
            except:
                pass
        else:
            return
        
        rect = win32gui.GetWindowRect(self.tdx_menu_system_hwnd)
        print('rect=',rect)
        self._mouse_click(rect[0] + 5, rect[1]+5)
        """
        self._click_rect(self.tdx_menu_system_hwnd,x_offset=5,y_offset=5,x_0='left',y_0='top')
        time.sleep(1)
        self._click_rect(self.tdx_menu_system_hwnd,x_offset=5,y_offset=230,x_0='left',y_0='bottom',foreground=False)
        if self.debug_enable: print('点击数据下载')
        """
        rect_new = (rect[0],rect[3],rect[2]+100,rect[3]+240)
        verify_code_image = ImageGrab.grab(rect_new)
        image_path = tempfile.mktemp() + '.jpg'
        verify_code_image.save(image_path)
        print('image_path=',image_path)
        time.sleep(1)
        
        download_x = rect[0] + 5
        download_y = rect[3] + 230
        self._mouse_click(download_x, download_y)
        time.sleep(1)
        """ 
Example 39
Project: pytrade   Author: allisnone   File: easytrader_tdx_api.py    GNU General Public License v2.0 5 votes vote down vote up
def _click_export_data(self):
        """
        print('self.tdx_menu_system_hwnd=',self.tdx_menu_system_hwnd)
        if self.tdx_menu_system_hwnd:
            try:
                self._set_foreground_window(self.tdx_menu_system_hwnd)
            except:
                pass
        else:
            return
        
        rect = win32gui.GetWindowRect(self.tdx_menu_system_hwnd)
        print('rect=',rect)
        self._mouse_click(rect[0] + 5, rect[1]+5)
        
        time.sleep(1)
        
        rect_new = (rect[0],rect[3],rect[2]+100,rect[3]+240)
        verify_code_image = ImageGrab.grab(rect_new)
        image_path = tempfile.mktemp() + '.jpg'
        verify_code_image.save(image_path)
        print('image_path=',image_path)
        time.sleep(1)
        export_data_x = rect[0] + 5
        export_data_y = rect[3] + 60
        self._mouse_click(export_data_x, export_data_y)
        time.sleep(5)
        """
        self._click_rect(self.tdx_menu_system_hwnd,x_offset=5,y_offset=5,x_0='left',y_0='top')
        time.sleep(1)
        self._click_rect(self.tdx_menu_system_hwnd,x_offset=5,y_offset=60,x_0='left',y_0='bottom',foreground=False)
        return 
Example 40
Project: pytrade   Author: allisnone   File: easytrader_tdx_api.py    GNU General Public License v2.0 5 votes vote down vote up
def _grab_verify_code(self):
        verify_code_hwnd = win32gui.GetDlgItem(self.login_hwnd, 0x0170)#0x4c8)#0x80BA)#0x56ba)
        self._set_foreground_window(self.login_hwnd)
        time.sleep(1)
        rect = win32gui.GetWindowRect(verify_code_hwnd)
        print('rect=',rect)
        rect = (rect[0],rect[1],rect[2]+30,rect[3])
        print('rect1=',rect)
        return ImageGrab.grab(rect) 
Example 41
Project: pytrade   Author: allisnone   File: easytrader_tdx_api.py    GNU General Public License v2.0 5 votes vote down vote up
def _click_login_button(self):
        time.sleep(1)
        input_hwnd = win32gui.GetDlgItem(self.login_hwnd, 0x1)
        #win32gui.SendMessage(input_hwnd, win32con.BM_CLICK, None, None)
        rect = win32gui.GetWindowRect(input_hwnd)
        self._mouse_click(rect[0] + 5, rect[1]+5)
        time.sleep(1)
        #tanchu_hwnd = win32gui.FindWindow(0, '关闭')# '消息标题:关于对证件有效期缺失的个人账户采取限制措施的公告')  # 交易窗口
        #tanchu_hwnd = findTopWindow()
        """
        tanchu_hwnd = 0
        print('tanchu_hwnd=',tanchu_hwnd)
        windows = dumpWindows(0)
        print('windows=',windows)
        for window in windows:
            #print(window)
            child_hwnd, window_text, window_class = window
            if '关闭' == window_text:
                tanchu_hwnd = child_hwnd
                break
        """
        #tanchu_hwnd0 = win32gui.FindWindow(0, '消息标题:关于对证件有效期缺失的个人账户采取限制措施的公告')  # 交易窗口
        title = '消息标题'
        tanchu_hwnd0 = get_exist_hwnd(hwnd=0,wantedText=title,exact_text=False)
        print('tanchu_hwnd0=',tanchu_hwnd0)
        #closePopupWindows(tanchu_hwnd0, wantedText=None, wantedClass=None)
        time.sleep(0.5)
        #tanchu_hwnd = get_exist_hwnd(hwnd=tanchu_hwnd0, wantedText='关闭',wantedClass='#32770')
        #print('tanchu_hwnd=',tanchu_hwnd)
        #time.sleep(0.5)
        if tanchu_hwnd0>0:
            click(tanchu_hwnd0)
            win32gui.SendMessage(tanchu_hwnd0, win32con.WM_CLOSE, None, None)
            time.sleep(0.2)
            #rect = win32gui.GetWindowRect(tanchu_hwnd)
            #self._mouse_click(rect[0] + 5, rect[1]+5) 
Example 42
Project: pytrade   Author: allisnone   File: winguiauto.py    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)
    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 43
Project: pytrade   Author: allisnone   File: yh_clienttrader.py    GNU General Public License v2.0 5 votes vote down vote up
def _click_login_verify_code(self):
        input_hwnd = win32gui.GetDlgItem(self.login_hwnd, 0x56ba)
        rect = win32gui.GetWindowRect(input_hwnd)
        self._mouse_click(rect[0] + 5, rect[1] + 5) 
Example 44
Project: pytrade   Author: allisnone   File: yh_clienttrader.py    GNU General Public License v2.0 5 votes vote down vote up
def _grab_verify_code(self):
        verify_code_hwnd = win32gui.GetDlgItem(self.login_hwnd, 0x56ba)
        self._set_foreground_window(self.login_hwnd)
        time.sleep(1)
        rect = win32gui.GetWindowRect(verify_code_hwnd)
        return ImageGrab.grab(rect) 
Example 45
Project: pyty   Author: howardjohn   File: window_api.py    GNU General Public License v3.0 5 votes vote down vote up
def get_window_rect(hwnd):
    """
    Gets the window's dimensions in the form Rect(x, y, w, h).

    Args:
        hwnd (int): The window handler.
    Returns:
        (Rect(x, y, w, h)): The dimensions of the window.
    """
    rect = wg.GetWindowRect(hwnd)
    return Rect(rect[0], rect[1], rect[2] - rect[0], rect[3] - rect[1]) 
Example 46
Project: PictureMatchCheater   Author: tianyigeng   File: UI.py    MIT License 5 votes vote down vote up
def getOrigin():
    cwllk = '宠物连连看'.decode('utf8')
    hwnd = win32gui.FindWindow("#32770", cwllk)
    print hwnd
    
    win32gui.ShowWindow(hwnd, win32con.SW_SHOWMINIMIZED)
    win32gui.ShowWindow(hwnd, win32con.SW_SHOWNORMAL)
    win32gui.SetForegroundWindow(hwnd)
    rect = win32gui.GetWindowRect(hwnd)
    time.sleep(0.5)
    print rect
    
    newRect = (rect[0] + 58, rect[1] + 104, rect[0] + 674, rect[1] + 504)
    
    return newRect 
Example 47
Project: PictureMatchCheater   Author: tianyigeng   File: UI.py    MIT License 5 votes vote down vote up
def getOrigin():
    cwllk = '宠物连连看'.decode('utf8')
    hwnd = win32gui.FindWindow("#32770", cwllk)
    print hwnd
    
    #win32gui.ShowWindow(hwnd, win32con.SW_SHOWMINIMIZED)
    win32gui.ShowWindow(hwnd, win32con.SW_SHOWNORMAL)
    win32gui.SetForegroundWindow(hwnd)
    rect = win32gui.GetWindowRect(hwnd)
    time.sleep(0.5)
    #print rect
    
    #newRect = (rect[0] + 58, rect[1] + 104, rect[0] + 674, rect[1] + 504)
    
    return rect 
Example 48
Project: bot   Author: maaaxim   File: functions.py    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 49
Project: Auto-Lianliankan   Author: TheThreeDog   File: run.py    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 50
Project: ATX   Author: NetEaseGame   File: windows.py    Apache License 2.0 5 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 51
Project: ATX   Author: NetEaseGame   File: windows.py    Apache License 2.0 5 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 52
Project: deep-nfshp   Author: vobject   File: grabscreen.py    MIT License 5 votes vote down vote up
def __init__(self, wnd_title: str, dst_size, src_offset, wnd_handle = None):
        """
        :parameter wnd_title: substring to search for in titles bars. required.
        :parameter regions: tuple of (top, left, height, width). None grabs whole screen.
        """
        self._search_str = wnd_title
        if wnd_handle:
            self._hwnd = wnd_handle
        else:
            # Look for window title, case sensitive.
            win32gui.EnumWindows(self.enumHandler, None)
            if self._hwnd == 0:
                message = "wnd_title '{}' not found.".format(wnd_title)
                raise ValueError(message)
        self._dst_size = dst_size
        self._src_offset = src_offset

        hwnd = self._hwnd
        l,t,r,b = win32gui.GetWindowRect(hwnd)
        h=b-t
        w=r-l

        if not self._dst_size:
            self._dst_size = (w, h)

        w_handle_DC = win32gui.GetWindowDC(hwnd)
        windowDC = win32ui.CreateDCFromHandle(w_handle_DC)
        memDC = windowDC.CreateCompatibleDC()

        dataBitMap = win32ui.CreateBitmap()
        dataBitMap.CreateCompatibleBitmap(windowDC , self._dst_size[0], self._dst_size[1])

        memDC.SelectObject(dataBitMap)

        self._w_handle_DC = w_handle_DC
        self._dataBitMap = dataBitMap
        self._memDC = memDC
        self._windowDC = windowDC
        self._src_size = (w - src_offset[0] - src_offset[2], h - src_offset[1] - src_offset[3])
        self._top  = t + src_offset[0]
        self._left = l + src_offset[1] 
Example 53
Project: KivyOnTop   Author: JakubBlaha   File: __init__.py    MIT License 5 votes vote down vote up
def set_always_on_top(title: str):
    '''
    Sets the HWND_TOPMOST flag for the current Kivy Window.
    This behavior will be overwritten by setting position of the window from kivy.
    If you want the window to stay on top of others even after changing the position or size from kivy, 
    use the register_topmost function instead.
    '''

    global hwnd

    if not 'hwnd' in globals():
        find_hwnd(title)

    rect = win32gui.GetWindowRect(hwnd)
    x = rect[0]
    y = rect[1]
    w = rect[2] - x
    h = rect[3] - y

    win32gui.SetWindowPos(hwnd, win32con.HWND_TOPMOST, x, y, w, h, 0) 
Example 54
Project: iamnotafk   Author: gbrlbsls   File: afk.py    MIT License 5 votes vote down vote up
def _get_window_info(self):
        if self.hwnd == None:
            return
        
        rect = win32gui.GetWindowRect(self.hwnd)
        self.x = rect[0]
        self.y = rect[1]
        self.w = rect[2] - self.x
        self.h = rect[3] - self.y 
Example 55
Project: arkScript   Author: akbchris   File: win32gui_dialog.py    MIT License 5 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 56
Project: arkScript   Author: akbchris   File: win32rcparser_demo.py    MIT License 5 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 57
Project: OpenAI_Challenges   Author: AlwaysLearningDeeper   File: grabscreen.py    MIT License 5 votes vote down vote up
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.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) 
Example 58
Project: play_as_one   Author: jaronoff97   File: PlayAsOne.py    MIT License 5 votes vote down vote up
def find_game_window(self):
        if sys.platform == 'win32':
            winlist = []

            def enum_cb(hwnd, extra):
                winlist.append((hwnd, win32gui.GetWindowText(hwnd)))
            win32gui.EnumWindows(enum_cb, None)

            window = [
                (hwnd, title) for hwnd, title in winlist if self.gui.titlebar_entry.get().lower() in title.lower()]
            if not window:
                return False
            window = window[0]
            hwnd = window[0]

            win32gui.ShowWindow(hwnd, 11)
            win32gui.ShowWindow(hwnd, 1)
            win32gui.SetForegroundWindow(hwnd)
            region = win32gui.GetWindowRect(hwnd)
            region = (
                region[0],
                region[1],
                region[2]-region[0],
                region[3]-region[1]
            )
            return region
        return False 
Example 59
Project: PyQt   Author: PyQt5   File: FollowWindow.py    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 60
Project: PyQt   Author: PyQt5   File: ProbeWindow.py    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 61
Project: https-github.com-TheThreeDog-Auto-Lianliankan   Author: BAIXINYI   File: run.py    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 62
Project: pyAutoTrading   Author: drongh   File: winguiauto.py    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 63
Project: csgo-autoaccept   Author: clugg   File: base.py    MIT License 5 votes vote down vote up
def screenshot(window_title):
    """
    Take a screenshot of the window if it exists.

    Returns:
        Image: Image data for the screenshot taken.
        bool: False if no window exists.
    """

    hwnd = get_hwnd(window_title)
    return ImageGrab.grab(win32gui.GetWindowRect(hwnd)) if hwnd else False 
Example 64
Project: eavatar-me   Author: eavatar   File: console.py    Apache License 2.0 5 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 65
Project: eavatar-me   Author: eavatar   File: notice_dlg.py    Apache License 2.0 5 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 66
Project: eavatar-me   Author: eavatar   File: simpledialog.py    Apache License 2.0 5 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 67
Project: Airtest   Author: AirtestProject   File: screen.py    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 68
Project: GTA5-AI-Playground   Author: Onixaz   File: grabscreen.py    GNU General Public License v3.0 4 votes vote down vote up
def grab_screen(region=None):

    #### for manual region grab ######

    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)

    #### for auto grab ####
    # hwin = win32gui.FindWindow(None, 'Grand Theft Auto V')
    # rect = win32gui.GetWindowRect(hwin)

    # x = rect[0]
    # y = rect[1]
    # left = 0
    # top = 40
    # height = rect[3] - y - top
    # width = rect[2] - x

    ###################
    #bmp.CreateCompatibleBitmap(srcdc, width, height)
    # win32ui.error: CreateCompatibleDC failed
    # if getting the error above, try the manual grab

    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)