Python win32gui.EnumWindows() Examples

The following are 30 code examples for showing how to use win32gui.EnumWindows(). 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: NGU-scripts   Author: kujan   File: window.py    License: GNU Lesser General Public License v3.0 6 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 2
Project: dragonfly   Author: t4ngo   File: window.py    License: GNU Lesser General Public License v3.0 6 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
Project: plex-mpv-shim   Author: iwalton3   File: win_utils.py    License: MIT License 6 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 4
Project: peach   Author: MozillaSecurity   File: file.py    License: 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 5
Project: peach   Author: MozillaSecurity   File: file.py    License: 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 6
Project: peach   Author: MozillaSecurity   File: process.py    License: 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
Project: peach   Author: MozillaSecurity   File: process.py    License: 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 8
Project: peach   Author: MozillaSecurity   File: process.py    License: 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 9
Project: peach   Author: MozillaSecurity   File: process.py    License: 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 10
Project: peach   Author: MozillaSecurity   File: process.py    License: 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 11
Project: ironpython2   Author: IronLanguages   File: win32gui_demo.py    License: 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 12
Project: ironpython2   Author: IronLanguages   File: winprocess.py    License: 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 13
Project: ironpython2   Author: IronLanguages   File: winprocess.py    License: 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 14
Project: dragonfly   Author: dictation-toolbox   File: win32_window.py    License: 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 
Example 15
Project: marsnake   Author: turingsec   File: winpty.py    License: GNU General Public License v3.0 5 votes vote down vote up
def get_hwnds_for_pid(pid):
    def callback(hwnd, hwnds):
        # if win32gui.IsWindowVisible(hwnd) and win32gui.IsWindowEnabled(hwnd):
        _, found_pid = win32process.GetWindowThreadProcessId(hwnd)
        # print hwnd
        if found_pid == pid:
            hwnds.append(hwnd)
        return True
    hwnds = []
    win32gui.EnumWindows(callback, hwnds)
    return hwnds 
Example 16
Project: pyautotrade_tdx   Author: ynzheng   File: winguiauto.py    License: 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 17
Project: PUBG   Author: xulusjb   File: main.py    License: The Unlicense 5 votes vote down vote up
def activegamewindow():

	gamepid = findgame()
	if gamepid is not None:
		win32gui.EnumWindows(enum_window_callback, gamepid) 
Example 18
Project: PUBG   Author: xulusjb   File: main.py    License: The Unlicense 5 votes vote down vote up
def crashwindow():
	top_windows = []
	win32gui.EnumWindows(windowEnumerationHandler, top_windows)
	for i in top_windows:
		if "BATTLEGROUNDS Crash Reporter" in i[1]:
			win32gui.PostMessage(i[0],win32con.WM_CLOSE,0,0)
			l("crash window closed")
			return True
	return False

# pyinput helper functions 
Example 19
Project: bot   Author: maaaxim   File: functions.py    License: MIT License 5 votes vote down vote up
def get_window_info():
    # set window info
    window_info = {}
    win32gui.EnumWindows(set_window_coordinates, window_info)
    return window_info


# EnumWindows handler
# sets L2 window coordinates 
Example 20
Project: peach   Author: MozillaSecurity   File: gui.py    License: Mozilla Public License 2.0 5 votes vote down vote up
def run(self):
            while not self.StopEvent.isSet():
                win32gui.EnumWindows(_WindowWatcher.enumCallback, self)
                time.sleep(.2) 
Example 21
Project: peach   Author: MozillaSecurity   File: tcp.py    License: Mozilla Public License 2.0 5 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:
                    return

                (threadId, processId) = win32process.GetWindowThreadProcessId(hwnd)

                # Send WM_CLOSE message
                try:
                    win32gui.PostMessage(hwnd, win32con.WM_CLOSE, 0, 0)
                    win32gui.PostQuitMessage(hwnd)
                except:
                    pass

                # Give it upto 5 sec
                for i in range(100):
                    if win32process.GetExitCodeProcess(processId) != win32con.STILL_ACTIVE:
                        # Process exited already
                        return

                    time.sleep(0.25)

                try:
                    # Kill application
                    win32process.TerminateProcess(processId, 0)
                except:
                    pass
            except:
                pass 
Example 22
Project: peach   Author: MozillaSecurity   File: tcp.py    License: Mozilla Public License 2.0 5 votes vote down vote up
def closeApp(self, title):
            """
            Close Application by window title
            """
            #print "CloseApp: %s" % title
            win32gui.EnumWindows(TcpListenerLaunchGui.enumCallback, title) 
Example 23
Project: PyAutoTrading   Author: bluestinger   File: winguiauto.py    License: 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 24
Project: PyAutoTrading   Author: bluestinger   File: winguiauto.py    License: 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 25
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 26
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 27
Project: fame_modules   Author: certsocietegenerale   File: cutthecrap.py    License: 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 28
Project: PyQt   Author: PyQt5   File: EmbedWindow.py    License: GNU General Public License v3.0 5 votes vote down vote up
def _getWindowList(self):
        """清空原来的列表"""
        self.windowList.clear()
        win32gui.EnumWindows(self._enumWindows, None) 
Example 29
Project: Poco   Author: AirtestProject   File: WindowsUI.py    License: 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 30
Project: Poco   Author: AirtestProject   File: WindowsUI.py    License: 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