Python win32gui.FindWindow() Examples

The following are 28 code examples for showing how to use win32gui.FindWindow(). These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.

You may also want to check out all available functions/classes of the module win32gui , or try the search function .

Example 1
Project: ironpython2   Author: IronLanguages   File: testExplorer.py    License: Apache License 2.0 6 votes vote down vote up
def TestObjectFromWindow():
    # Check we can use ObjectFromLresult to get the COM object from the
    # HWND - see KB Q249232
    # Locating the HWND is different than the KB says...
    hwnd = win32gui.FindWindow('IEFrame', None)
    for child_class in ['TabWindowClass', 'Shell DocObject View',
                        'Internet Explorer_Server']:
        hwnd = win32gui.FindWindowEx(hwnd, 0, child_class, None)
        assert hwnd, "Couldn't find '%s'" % (child_class,)
    # But here is the point - once you have an 'Internet Explorer_Server',
    # you can send a message and use ObjectFromLresult to get it back.
    msg = win32gui.RegisterWindowMessage("WM_HTML_GETOBJECT")
    rc, result = win32gui.SendMessageTimeout(hwnd, msg, 0, 0, win32con.SMTO_ABORTIFHUNG, 1000)
    ob = pythoncom.ObjectFromLresult(result, pythoncom.IID_IDispatch, 0)
    doc = Dispatch(ob)
    # just to prove it works, set the background color of the document.
    for color in "red green blue orange white".split():
        doc.bgColor = color
        time.sleep(0.2) 
Example 2
Project: poeai   Author: nicholastoddsmith   File: ScreenViewer.py    License: 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 3
Project: ironpython2   Author: IronLanguages   File: desktopmanager.py    License: Apache License 2.0 5 votes vote down vote up
def new_icon(hdesk,desktop_name):
    """ Runs as a thread on each desktop to create a new tray icon and handle its messages """ 
    global id
    id=id+1
    hdesk.SetThreadDesktop()
    ## apparently the threads can't use same hinst, so each needs its own window class
    windowclassname='PythonDesktopManager'+desktop_name
    wc = win32gui.WNDCLASS()
    wc.hInstance = win32api.GetModuleHandle(None)
    wc.lpszClassName = windowclassname
    wc.style = win32con.CS_VREDRAW | win32con.CS_HREDRAW | win32con.CS_GLOBALCLASS
    wc.hCursor = win32gui.LoadCursor( 0, win32con.IDC_ARROW )
    wc.hbrBackground = win32con.COLOR_WINDOW
    wc.lpfnWndProc = icon_wndproc
    windowclass = win32gui.RegisterClass(wc)
    style = win32con.WS_OVERLAPPED | win32con.WS_SYSMENU
    hwnd = win32gui.CreateWindow(windowclass, 'dm_'+desktop_name, win32con.WS_SYSMENU,
                    0, 0, win32con.CW_USEDEFAULT, win32con.CW_USEDEFAULT,
                    0, 0, wc.hInstance, None)
    win32gui.UpdateWindow(hwnd)
    flags = win32gui.NIF_ICON | win32gui.NIF_MESSAGE | win32gui.NIF_TIP
    notify_info = (hwnd, id, flags, win32con.WM_USER+20, hicon, 'Desktop Manager (%s)' %desktop_name)
    window_info[hwnd]=notify_info
    ## wait for explorer to initialize system tray for new desktop
    tray_found=0
    while not tray_found:
        try:
            tray_found=win32gui.FindWindow("Shell_TrayWnd",None)
        except win32gui.error:
            traceback.print_exc
            time.sleep(.5)
    win32gui.Shell_NotifyIcon(win32gui.NIM_ADD, notify_info)
    win32gui.PumpMessages() 
Example 4
Project: Automatic-minesweeping   Author: buaazyc   File: window.py    License: 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 5
Project: roc   Author: Sunuba   File: Clicker.py    License: MIT License 5 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 6
Project: roc   Author: Sunuba   File: Screenshot.py    License: MIT License 5 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 7
Project: pyautotrade_tdx   Author: ynzheng   File: winguiauto.py    License: GNU General Public License v2.0 5 votes vote down vote up
def findTopWindow(wantedText=None, wantedClass=None):
    '''
    :param wantedText: 标题名字
    :param wantedClass: 窗口类名
    :return: 返回顶层窗口的句柄
    '''
    return win32gui.FindWindow(wantedClass, wantedText) 
Example 8
Project: bqt   Author: techartorg   File: win32_blender_application.py    License: Mozilla Public License 2.0 5 votes vote down vote up
def _get_application_hwnd() -> int:
        """
        This finds the blender application window and collects the
        handler window ID

        Returns int: Handler Window ID
        """

        hwnd = win32gui.FindWindow(None, 'blender')
        return hwnd 
Example 9
Project: PyAutoTrading   Author: bluestinger   File: winguiauto.py    License: GNU General Public License v2.0 5 votes vote down vote up
def findSpecifiedTopWindow(wantedText=None, wantedClass=None):
    '''
    :param wantedText: 标题名字
    :param wantedClass: 窗口类名
    :return: 返回顶层窗口的句柄
    '''
    return win32gui.FindWindow(wantedClass, wantedText) 
Example 10
Project: Auto-Lianliankan   Author: TheThreeDog   File: run.py    License: 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 11
Project: ATX   Author: NetEaseGame   File: windows.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, window_name=None, exe_file=None, exclude_border=True):
        hwnd = 0

        # first check window_name
        if window_name is not None:
            hwnd = win32gui.FindWindow(None, window_name)
            if hwnd == 0:
                def callback(h, extra):
                    if window_name in win32gui.GetWindowText(h):
                        extra.append(h)
                    return True
                extra = []
                win32gui.EnumWindows(callback, extra)
                if extra: hwnd = extra[0]
            if hwnd == 0:
                raise WindowsAppNotFoundError("Windows Application <%s> not found!" % window_name)

        # check exe_file by checking all processes current running.
        elif exe_file is not None:
            pid = find_process_id(exe_file)
            if pid is not None:
                def callback(h, extra):
                    if win32gui.IsWindowVisible(h) and win32gui.IsWindowEnabled(h):
                        _, p = win32process.GetWindowThreadProcessId(h)
                        if p == pid:
                            extra.append(h)
                        return True
                    return True
                extra = []
                win32gui.EnumWindows(callback, extra)
                #TODO: get main window from all windows.
                if extra: hwnd = extra[0]
            if hwnd == 0:
                raise WindowsAppNotFoundError("Windows Application <%s> is not running!" % exe_file)

        # if window_name & exe_file both are None, use the screen.
        if hwnd == 0:
            hwnd = win32gui.GetDesktopWindow()

        self.hwnd = hwnd
        self.exclude_border = exclude_border 
Example 12
Project: imoocc   Author: iopsgroup   File: win_pageant.py    License: GNU General Public License v2.0 5 votes vote down vote up
def _get_pageant_window_object():
    if _has_win32all:
        try:
            hwnd = win32gui.FindWindow('Pageant', 'Pageant')
            return hwnd
        except win32gui.error:
            pass
    elif _has_ctypes:
        # Return 0 if there is no Pageant window.
        return ctypes.windll.user32.FindWindowA('Pageant', 'Pageant')
    return None 
Example 13
Project: imoocc   Author: iopsgroup   File: win_pageant.py    License: GNU General Public License v2.0 5 votes vote down vote up
def _get_pageant_window_object():
    if _has_win32all:
        try:
            hwnd = win32gui.FindWindow('Pageant', 'Pageant')
            return hwnd
        except win32gui.error:
            pass
    elif _has_ctypes:
        # Return 0 if there is no Pageant window.
        return ctypes.windll.user32.FindWindowA('Pageant', 'Pageant')
    return None 
Example 14
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 15
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 16
Project: PyQt   Author: PyQt5   File: FollowWindow.py    License: 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 17
Project: onmyoji_bot   Author: AcademicDog   File: game_ctl.py    License: GNU General Public License v3.0 5 votes vote down vote up
def main():
    hwnd = win32gui.FindWindow(0, u'阴阳师-网易游戏')
    yys = GameControl(hwnd, 0)
    yys.debug() 
Example 18
Project: pyautotrade_tdx   Author: wangdkchina   File: winguiauto.py    License: GNU General Public License v2.0 5 votes vote down vote up
def findSpecifiedTopWindow(wantedText=None, wantedClass=None):
    '''
    :param wantedText: 标题名字
    :param wantedClass: 窗口类名
    :return: 返回顶层窗口的句柄
    '''
    return win32gui.FindWindow(wantedClass, wantedText) 
Example 19
Project: pyAutoTrading   Author: drongh   File: winguiauto.py    License: GNU General Public License v2.0 5 votes vote down vote up
def findTopWindow(wantedText=None, wantedClass=None):
    """
    :param wantedText: 标题名字
    :param wantedClass: 窗口类名
    :return: 返回顶层窗口的句柄
    """
    return win32gui.FindWindow(wantedClass, wantedText) 
Example 20
Project: EventGhost   Author: EventGhost   File: __init__.py    License: GNU General Public License v2.0 5 votes vote down vote up
def isRunning(self):
        try:
            return FindWindow(u'MediaPlayerClassicW', None)
        except:
            return False 
Example 21
Project: EventGhost   Author: EventGhost   File: __init__.py    License: GNU General Public License v2.0 5 votes vote down vote up
def BringDialogToFront(name):
        hwnd = 0
        i = 0
        while hwnd == 0 and i < 10000:
            hwnd = FindWindow("#32770", name)
            i += 1
        if hwnd:
            BringHwndToFront(hwnd) 
Example 22
Project: EventGhost   Author: EventGhost   File: __init__.py    License: GNU General Public License v2.0 5 votes vote down vote up
def SendCommand(mesg, wParam, lParam=0):
    """
    Find DScaler's message window
    """
    try:
        hDScaler = FindWindow('DScaler', None)
        _, result = SendMessageTimeout(hDScaler, mesg, wParam, lParam,
                                       SMTO_BLOCK|SMTO_ABORTIFHUNG, 2000)
        return result
    except:
        raise self.Exception.ProgramNotRunning 
Example 23
Project: EventGhost   Author: EventGhost   File: __init__.py    License: GNU General Public License v2.0 5 votes vote down vote up
def controlMeedio(inputVal):
    try:
      hMeedioWnd = win32gui.FindWindow('H2-WM-COMMAND', None)
      return win32gui.SendMessage(hMeedioWnd, 273, inputVal, 0)
    except Exception:
      pass 
Example 24
Project: EventGhost   Author: EventGhost   File: __init__.py    License: GNU General Public License v2.0 5 votes vote down vote up
def isRunning(self):
        try:
            return FindWindow("TFMainWindow", "MediaMonkey") > 0
        except:
            return False 
Example 25
Project: Yugioh-bot   Author: will7200   File: steam.py    License: MIT License 5 votes vote down vote up
def is_process_running(self):
        try:
            self.win_handle = win32gui.FindWindow(None, self.predefined.window_name)
        except:
            return False
        if self.win_handle:
            return True
        return False 
Example 26
Project: Yugioh-bot   Author: will7200   File: nox.py    License: MIT License 5 votes vote down vote up
def is_process_running(self):
        try:
            if win32gui.FindWindow(None, "Nox") or win32gui.FindWindow(None, "NoxPlayer"):
                return True
        except:
            return False 
Example 27
Project: SwSpotify   Author: SwagLyrics   File: spotify.py    License: MIT License 4 votes vote down vote up
def get_info_windows():
    """
    Reads the window titles to get the data.

    Older Spotify versions simply use FindWindow for "SpotifyMainWindow",
    the newer ones create an EnumHandler and flood the list with
    Chrome_WidgetWin_0s
    """

    import win32gui

    windows = []

    old_window = win32gui.FindWindow("SpotifyMainWindow", None)
    old = win32gui.GetWindowText(old_window)

    def find_spotify_uwp(hwnd, windows):
        text = win32gui.GetWindowText(hwnd)
        classname = win32gui.GetClassName(hwnd)
        if classname == "Chrome_WidgetWin_0" and len(text) > 0:
            windows.append(text)

    if old:
        windows.append(old)
    else:
        win32gui.EnumWindows(find_spotify_uwp, windows)

    # If Spotify isn't running the list will be empty
    if len(windows) == 0:
        raise SpotifyClosed

    # Local songs may only have a title field
    try:
        artist, track = windows[0].split(" - ", 1)
    except ValueError:
        artist = ''
        track = windows[0]

    # The window title is the default one when paused
    if windows[0].startswith('Spotify'):
        raise SpotifyPaused

    return track, artist 
Example 28
Project: onmyoji_bot   Author: AcademicDog   File: fighter.py    License: GNU General Public License v3.0 4 votes vote down vote up
def __init__(self, emyc=0, hwnd=0):
        '''
        初始化
            : param emyc=0: 点怪设置:0-不点怪
            : param hwnd=0: 指定窗口句柄:0-否;其他-窗口句柄
        '''
        # 初始参数
        self.emyc = emyc
        self.run = True

        # 读取配置文件
        conf = configparser.ConfigParser()
        conf.read('conf.ini')
        self.client = conf.getint('DEFAULT', 'client')
        quit_game_enable = conf.getboolean('watchdog', 'watchdog_enable')
        self.max_op_time = conf.getint('watchdog', 'max_op_time')
        self.max_win_time = conf.getint('watchdog', 'max_win_time')
        self.mitama_team_mark = conf.getint('mitama', 'mitama_team_mark')
        self.max_times = conf.getint('DEFAULT', 'max_times')
        self.end_operation = conf.getint('DEFAULT', 'end_operation')
        self.run_times = 0

        # 启动日志
        self.log = MyLog.mlogger

        # 绑定窗口
        if hwnd == 0:
            if self.client == 0:
                hwnd = win32gui.FindWindow(0, u'阴阳师-网易游戏')
            elif self.client == 1:
                hwnd = win32gui.FindWindow(0, u'阴阳师 - MuMu模拟器')
                # TansuoPos.InitPosWithClient__()
                # YuhunPos.InitPosWithClient__()
        self.yys = GameControl(hwnd, quit_game_enable)
        self.log.info('绑定窗口成功')
        self.log.info(str(hwnd))

        # 激活窗口
        self.yys.activate_window()
        self.log.info('激活窗口成功')
        time.sleep(0.5)

        # 绑定场景

        # 自检
        debug_enable = conf.getboolean('others', 'debug_enable')
        if debug_enable:
            task = threading.Thread(target=self.yys.debug)
            task.start()