Python win32gui.EnumWindows() Examples

The following are 30 code examples of win32gui.EnumWindows(). 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: win_utils.py    From plex-mpv-shim with MIT License 8 votes vote down vote up
def raise_mpv():
    # This workaround is madness. Apparently SetForegroundWindow
    # won't work randomly, so I have to call ShowWindow twice.
    # Once to hide the window, and again to successfully raise the window.
    try:
        top_windows = []
        fg_win = win32gui.GetForegroundWindow()
        win32gui.EnumWindows(windowEnumerationHandler, top_windows)
        for i in top_windows:
            if " - mpv" in i[1].lower():
                if i[0] != fg_win:
                    win32gui.ShowWindow(i[0], 6) # Minimize
                    win32gui.ShowWindow(i[0], 9) # Un-minimize
                break

    except Exception:
        print("Could not raise MPV.")
        traceback.print_exc() 
Example #2
Source File: window.py    From dragonfly with GNU Lesser General Public License v3.0 7 votes vote down vote up
def get_all_windows(cls):
        def function(handle, argument):
            argument.append(Window(handle))
        argument = []
        win32gui.EnumWindows(function, argument)
        return argument

#    @classmethod
#    def get_window_by_executable(cls, executable):
#        def function(handle, argument):
#            title = windll.user32.GetWindowText(handle)
#            print "title: %r" % title
#        windll.user32.EnumWindows(function, argument)


    #=======================================================================
    # Methods for initialization and introspection. 
Example #3
Source File: process.py    From peach with Mozilla Public License 2.0 6 votes vote down vote up
def enumChildCallback(hwnd, windowName):
            """
            Will get called by win32gui.EnumWindows, once for each
            top level application window.
            """

            try:

                # Get window title
                title = win32gui.GetWindowText(hwnd)

                # Is this our guy?
                if title.find(windowName) == -1:
                    return

                # Send WM_CLOSE message
                win32gui.PostMessage(hwnd, win32con.WM_CLOSE, 0, 0)

            except:
                pass
            #print sys.exc_info() 
Example #4
Source File: process.py    From peach with Mozilla Public License 2.0 6 votes vote down vote up
def closeApp(self, hProcess, title):
            """
            Close Application by window title
            """

            try:
                win32gui.EnumWindows(FileWriterLauncherGui.enumCallback, title)

                if proc is not None:
                    win32event.WaitForSingleObject(hProcess, 5 * 1000)
                    win32api.CloseHandle(hProcess)

                    for pid in self.genChildProcesses(proc):
                        try:
                            handle = win32api.OpenProcess(1, False, pid)
                            win32process.TerminateProcess(handle, -1)
                            win32api.CloseHandle(handle)
                        except:
                            pass

            except:
                pass 
Example #5
Source File: process.py    From peach with Mozilla Public License 2.0 6 votes vote down vote up
def enumChildCallback(hwnd, windowName):
            """
            Will get called by win32gui.EnumWindows, once for each
            top level application window.
            """

            try:

                # Get window title
                title = win32gui.GetWindowText(hwnd)

                # Is this our guy?
                if title.find(windowName) == -1:
                    return

                # Send WM_CLOSE message
                win32gui.PostMessage(hwnd, win32con.WM_CLOSE, 0, 0)

            except:
                pass
            #print sys.exc_info() 
Example #6
Source File: process.py    From peach with Mozilla Public License 2.0 6 votes vote down vote up
def enumCallback(hwnd, windowName):
            """
            Will get called by win32gui.EnumWindows, once for each
            top level application window.
            """

            try:
                # Get window title
                title = win32gui.GetWindowText(hwnd)

                # Is this our guy?
                if title.find(windowName) == -1:
                    win32gui.EnumChildWindows(hwnd, FileWriterLauncherGui.enumChildCallback, windowName)
                    return

                # Send WM_CLOSE message
                win32gui.PostMessage(hwnd, win32con.WM_CLOSE, 0, 0)
            except:
                pass 
Example #7
Source File: file.py    From peach with Mozilla Public License 2.0 6 votes vote down vote up
def enumChildCallback(hwnd, args):
            """
            Will get called by win32gui.EnumWindows, once for each
            top level application window.
            """

            proc = args[0]
            windowName = args[1]

            try:

                # Get window title
                title = win32gui.GetWindowText(hwnd)

                # Is this our guy?
                if title.find(windowName) == -1:
                    return

                # Send WM_CLOSE message
                win32gui.PostMessage(hwnd, win32con.WM_CLOSE, 0, 0)

            except:
                pass
            #print sys.exc_info() 
Example #8
Source File: file.py    From peach with Mozilla Public License 2.0 6 votes vote down vote up
def enumCallback(hwnd, args):
            """
            Will get called by win32gui.EnumWindows, once for each
            top level application window.
            """

            proc = args[0]
            windowName = args[1]

            try:
                # Get window title
                title = win32gui.GetWindowText(hwnd)

                # Is this our guy?
                if title.find(windowName) == -1:
                    win32gui.EnumChildWindows(hwnd, FileWriterLauncherGui.enumChildCallback, args)
                    return

                # Send WM_CLOSE message
                win32gui.PostMessage(hwnd, win32con.WM_CLOSE, 0, 0)
            except:
                pass 
Example #9
Source File: windows.py    From ATX with Apache License 2.0 6 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 #10
Source File: WindowsUI.py    From Poco with Apache License 2.0 5 votes vote down vote up
def EnumWindows(self):
        hWndList = []  # 枚举所有窗口,并把有效窗口handle保存在hwndlist里

        def foo(hwnd, mouse):
            if win32gui.IsWindow(hwnd):
                hWndList.append(hwnd)
        win32gui.EnumWindows(foo, 0)
        return hWndList 
Example #11
Source File: winguiauto.py    From PyAutoTrading with GNU General Public License v2.0 5 votes vote down vote up
def _windowEnumerationHandler(hwnd, resultList):
    '''Pass to win32gui.EnumWindows() to generate list of window handle,
    window text, window class tuples.'''
    resultList.append((hwnd,
                       win32gui.GetWindowText(hwnd),
                       win32gui.GetClassName(hwnd))) 
Example #12
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 get_window_list():
    titles = []
    t = []
    pidList = [(p.pid, p.name()) for p in psutil.process_iter()]

    def enumWindowsProc(hwnd, lParam):
        """ append window titles which match a pid """
        if (lParam is None) or ((lParam is not None) and (win32process.GetWindowThreadProcessId(hwnd)[1] == lParam)):
            text = win32gui.GetWindowText(hwnd)
            if text:
                wStyle = win32api.GetWindowLong(hwnd, win32con.GWL_STYLE)
                if wStyle & win32con.WS_VISIBLE:
                    t.append("%s" % (text))
                    return

    def enumProcWnds(pid=None):
        win32gui.EnumWindows(enumWindowsProc, pid)

    for pid, pName in pidList:
        enumProcWnds(pid)
        if t:
            for title in t:
                titles.append("('{0}', '{1}')".format(pName, title))
            t = []
    titles = sorted(titles, key=lambda x: x[0].lower())
    return titles 
Example #13
Source File: cutthecrap.py    From fame_modules with GNU General Public License v3.0 5 votes vote down vote up
def run(self):
        while self.should_run():
            win32gui.EnumWindows(self.foreach_window(), 0)
            self._stop.wait(0.5) 
Example #14
Source File: EmbedWindow.py    From PyQt with GNU General Public License v3.0 5 votes vote down vote up
def _getWindowList(self):
        """清空原来的列表"""
        self.windowList.clear()
        win32gui.EnumWindows(self._enumWindows, None) 
Example #15
Source File: win32_helper.py    From pySPM with Apache License 2.0 5 votes vote down vote up
def _windowEnumerationHandler(hwnd, resultList):
    '''Pass to win32gui.EnumWindows() to generate list of window handle,
    window text, window class tuples.'''
    resultList.append((hwnd,
                       win32gui.GetWindowText(hwnd),
                       win32gui.GetClassName(hwnd))) 
Example #16
Source File: WindowsUI.py    From Poco with Apache License 2.0 5 votes vote down vote up
def ConnectWindowsByTitle(self, title):
        hn = set()  # 匹配窗口的集合,把所有标题匹配上的窗口handle都保存在这个集合里
        hWndList = self.EnumWindows()
        for handle in hWndList:
            title_temp = win32gui.GetWindowText(handle)
            if PY2:
                title_temp = title_temp.decode("gbk")  # py2要解码成GBK,WindowsAPI中文返回的一般都是GBK
            if title == title_temp:
                hn.add(handle)
        if len(hn) == 0:
            return -1
        return hn 
Example #17
Source File: WindowsUI.py    From Poco with Apache License 2.0 5 votes vote down vote up
def ConnectWindowsByTitleRe(self, title_re):
        hn = set()  # 匹配窗口的集合,把所有标题(正则表达式)匹配上的窗口handle都保存在这个集合里
        hWndList = self.EnumWindows()
        for handle in hWndList:
            title = win32gui.GetWindowText(handle)
            if PY2:
                title = title.decode("gbk")
            if re.match(title_re, title):
                hn.add(handle)
        if len(hn) == 0:
            return -1
        return hn 
Example #18
Source File: WindowsUI.py    From Poco with Apache License 2.0 5 votes vote down vote up
def ConnectWindowsByHandle(self, handle):
        hn = set()  # 匹配窗口的集合,把所有handle匹配上的窗口handle都保存在这个集合里
        hWndList = self.EnumWindows()
        for handle_temp in hWndList:
            if int(handle_temp) == int(handle):
                hn.add(handle)
                break
        if len(hn) == 0:
            return -1
        return hn 
Example #19
Source File: explore_dual.py    From onmyoji_bot with GNU General Public License v3.0 5 votes vote down vote up
def get_game_hwnd():
    win32gui.EnumWindows(get_all_hwnd, 0) 
Example #20
Source File: dual.py    From onmyoji_bot with GNU General Public License v3.0 5 votes vote down vote up
def get_game_hwnd():
    win32gui.EnumWindows(get_all_hwnd, 0) 
Example #21
Source File: winguiauto.py    From pyautotrade_tdx with GNU General Public License v2.0 5 votes vote down vote up
def findTopWindows(wantedText=None, wantedClass=None, selectionFunction=None):
    '''Find the hwnd of top level windows.
    
    You can identify windows using captions, classes, a custom selection
    function, or any combination of these. (Multiple selection criteria are
    ANDed. If this isn't what's wanted, use a selection function.)

    Parameters
    ----------
    wantedText          
        Text which required windows' captions must contain.
    wantedClass         
        Class to which required windows must belong.
    selectionFunction   
        Window selection function. Reference to a function
        should be passed here. The function should take hwnd as
        an argument, and should return True when passed the
        hwnd of a desired window.

    Returns
    -------
    A list containing the window handles of all top level
    windows matching the supplied selection criteria.

    Usage example::
        
        optDialogs = findTopWindows(wantedText="Options")
    '''
    results = []
    topWindows = []
    win32gui.EnumWindows(_windowEnumerationHandler, topWindows)
    for hwnd, windowText, windowClass in topWindows:
        if wantedText and not _normaliseText(wantedText) in _normaliseText(windowText):
            continue
        if wantedClass and not windowClass == wantedClass:
            continue
        if selectionFunction and not selectionFunction(hwnd):
            continue
        results.append(hwnd)
    return results 
Example #22
Source File: winguiauto.py    From pyautotrade_tdx with GNU General Public License v2.0 5 votes vote down vote up
def _windowEnumerationHandler(hwnd, resultList):
    '''Pass to win32gui.EnumWindows() to generate list of window handle,
    window text, window class tuples.'''
    resultList.append((hwnd,
                       win32gui.GetWindowText(hwnd),
                       win32gui.GetClassName(hwnd))) 
Example #23
Source File: winguiauto.py    From pyAutoTrading with GNU General Public License v2.0 5 votes vote down vote up
def _windowEnumerationHandler(hwnd, resultList):
    """Pass to win32gui.EnumWindows() to generate list of window handle,
    window text, window class tuples."""
    resultList.append((hwnd,
                       win32gui.GetWindowText(hwnd),
                       win32gui.GetClassName(hwnd))) 
Example #24
Source File: win32_helper.py    From pySPM with Apache License 2.0 5 votes vote down vote up
def findTopWindows(wantedText=None, wantedClass=None, selectionFunction=None):
    results = []
    topWindows = []
    win32gui.EnumWindows(_windowEnumerationHandler, topWindows)
    for hwnd, windowText, windowClass in topWindows:
        if wantedText and not _normaliseText(wantedText) in _normaliseText(windowText):
            continue
        if wantedClass and not windowClass == wantedClass:
            continue
        if selectionFunction and not selectionFunction(hwnd):
            continue
        results.append(hwnd)
    return results 
Example #25
Source File: window.py    From NGU-scripts with GNU Lesser General Public License v3.0 5 votes vote down vote up
def init(debug :bool =False) -> Dict[int, Tuple[int, int, int, int]]:
        """Finds the game window and returns its coords."""
        if platform.release() == "10":
            ctypes.windll.shcore.SetProcessDpiAwareness(2)
        else:
            ctypes.windll.user32.SetProcessDPIAware()

        def window_enumeration_handler(hwnd, top_windows):
            """Add window title and ID to array."""
            top_windows.append((hwnd, win32gui.GetWindowText(hwnd)))

        if debug:
            window_name = "debugg"
        else:
            window_name = "play ngu idle"

        top_windows = []
        windows = []
        candidates = {}
        win32gui.EnumWindows(window_enumeration_handler, top_windows)
        windows = [window[0] for window in top_windows if window_name in window[1].lower()]
        for window in windows:
            candidates[window] = Window.winRect(window)
        return candidates 
Example #26
Source File: winguiauto.py    From pyautotrade_tdx with GNU General Public License v2.0 5 votes vote down vote up
def _windowEnumerationHandler(hwnd, resultList):
    '''Pass to win32gui.EnumWindows() to generate list of window handle,
    window text, window class tuples.'''
    resultList.append((hwnd,
                       win32gui.GetWindowText(hwnd),
                       win32gui.GetClassName(hwnd))) 
Example #27
Source File: win32gui_demo.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def TestEnumWindows():
    windows = []
    classes = {}
    win32gui.EnumWindows(_MyCallback, (windows, classes))
    print "Enumerated a total of %d windows with %d classes" % (len(windows),len(classes))
    if "tooltips_class32" not in classes:
        print "Hrmmmm - I'm very surprised to not find a 'tooltips_class32' class." 
Example #28
Source File: winprocess.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def kill(self, gracePeriod=5000):
        """
        Kill process. Try for an orderly shutdown via WM_CLOSE.  If
        still running after gracePeriod (5 sec. default), terminate.
        """
        win32gui.EnumWindows(self.__close__, 0)
        if self.wait(gracePeriod) != win32event.WAIT_OBJECT_0:
            win32process.TerminateProcess(self.hProcess, 0)
            win32api.Sleep(100) # wait for resources to be released 
Example #29
Source File: winprocess.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def __close__(self, hwnd, dummy):
        """
        EnumWindows callback - sends WM_CLOSE to any window
        owned by this process.
        """
        TId, PId = win32process.GetWindowThreadProcessId(hwnd)
        if PId == self.PId:
            win32gui.PostMessage(hwnd, win32con.WM_CLOSE, 0, 0) 
Example #30
Source File: win32_window.py    From dragonfly with GNU Lesser General Public License v3.0 5 votes vote down vote up
def get_all_windows(cls):
        def function(handle, argument):
            argument.append(cls.get_window(handle))
        argument = []
        win32gui.EnumWindows(function, argument)
        return argument