def show(stopEvent: Event, handle: List[int]): with auto.UIAutomationInitializerInThread(): for handle in handles: win = auto.ControlFromHandle(handle) win.Show(0) if auto.IsIconic(handle): win.ShowWindow(auto.SW.Restore, 0)
def refreshDict(): console = uiautomation.GetConsoleWindow() # new handle global nextHandleKey log('nextHandleKey = ' + str(nextHandleKey)) begHandle = 0 while True: window = uiautomation.WindowControl(searchDepth=1, ClassName='WeChatMainWndForPC', SubName=u'微信') window.ShowWindow(uiautomation.ShowWindow.Maximize) #window.SetActive() curHandle = window.Handle if begHandle == 0 : begHandle = curHandle elif begHandle == curHandle : break if curHandle not in handleDict.values(): handleDict[nextHandleKey] = curHandle log('add: ' + str(nextHandleKey) + ' ' + str(curHandle)) nextHandleKey += 1 window.SendKeys('{ALT}{ESC}') console.SetActive() # invalid handle keyList = handleDict.copy().keys() for index in keyList: curHandle = handleDict[index] window = uiautomation.ControlFromHandle(curHandle) if window == None: handleDict.pop(index) log('pop: ' + str(index) + ' ' + str(curHandle)) log('dice is refreshed: len=' + str(len(handleDict)) + ' nextHandleKey='+str(nextHandleKey))
def ConnectWindow(self, selector, foreground=False): if foreground: time.sleep(1) self.root = UIAuto.GetForegroundControl() return True handleSetList = [] if 'title' in selector: handleSetList.append(self.ConnectWindowsByTitle(selector['title'])) if 'handle' in selector: handleSetList.append(self.ConnectWindowsByHandle(selector['handle'])) if "title_re" in selector: handleSetList.append(self.ConnectWindowsByTitleRe(selector['title_re'])) while -1 in handleSetList: handleSetList.remove(-1) if len(handleSetList) == 0: return False handleSet = handleSetList[0] for s in handleSetList: handleSet = s & handleSet if len(handleSet) == 0: return False elif len(handleSet) != 1: raise NonuniqueSurfaceException(selector) else: hn = handleSet.pop() if hn: self.root = UIAuto.ControlFromHandle(hn) return True else: return False
def get_chrome_tab_name(): window = win32gui.GetForegroundWindow() chrome_control = auto.ControlFromHandle(window) edit = chrome_control.EditControl() return chrome_control.Name[:chrome_control.Name.find(' - Google')]
def get_browser_url(): if sys.platform in ['Windows', 'win32', 'cygwin']: window = win32gui.GetForegroundWindow() chromeControl = auto.ControlFromHandle(window) edit = chromeControl.EditControl() return 'https://' + edit.GetValuePattern().Value return _active_window_name
def get_qrcode(handle): # # 点击多开 # duokai = uiautomation.WindowControl(searchDepth=1, SubName=u'电脑端微信多开') # duokai.SetActive() # time.sleep(1) # # edit = duokai.EditControl(LocalizedControlType=u'编辑') # # edit.Click(simulateMove=False) # # duokai.SendKeys('{Home}'+'{Shift}{End}'+'C:\\WeChat') # qidong = duokai.ButtonControl(Name=u'启动微信') # qidong.Click(simulateMove=False) # 获取二维码 # wxlogin = uiautomation.PaneControl(searchDepth=2, ClassName='WeChatLoginWndForPC', Name=u'登录') wxlogin = uiautomation.ControlFromHandle(handle) time.sleep(0.1) ret = uiautomation.Win32API.SetForegroundWindow(handle) log('ret: ' + str(ret)) time.sleep(0.1) # 可能是已登录,所以点击“切换账号” # time.sleep(1) # wxlogin.Click(ratioY=0.9, simulateMove=False) # time.sleep(3) qrfile = 'qr/qr.png' wxlogin.CaptureToImage(qrfile, x=45, y=80, width=190, height=190) wxlogin.SendKeys('{ALT}{ESC}') f = open(qrfile, 'rb') b = f.read() f.close() return b
def chromeUrl(self): # get url from chrome window = win32gui.GetForegroundWindow() # Refrence : chromeControl = auto.ControlFromHandle(window) # https://stackoverflow.com/questions/59595763/get-active-chrome-url-in-python chromeWindow = chromeControl.EditControl() # "Get Active Chrome URL in Python" try: return '' + chromeWindow.GetValuePattern().Value except: return ''
def show(stopEvent: Event, handle: List[int]): #_uiobj = auto.UIAutomationInitializerInThread() # Show doesn't call any COM methods, so it doesn't need an UIAutomationInitializerInThread for handle in handles: win = auto.ControlFromHandle(handle) win.Show(0) if auto.IsIconic(handle): win.ShowWindow(auto.SW.Restore, 0)
def getWebsite(win): try: control = auto.ControlFromHandle(win) edit = control.EditControl() # print(edit.GetValuePattern().Value) website = str(edit.GetValuePattern().Value).split('/')[0] except: website = "-" return website
def show(): fout = open('hide_windows.txt') lines = fout.readlines() fout.close() for line in lines: handle = int(line) window = automation.ControlFromHandle(handle) if window: automation.Logger.WriteLine('show window: {}'.format(handle)) window.Show()
def get_chrome_url(): if sys.platform in ['Windows', 'win32', 'cygwin']: window = win32gui.GetForegroundWindow() chromeControl = auto.ControlFromHandle(window) edit = chromeControl.EditControl() return 'https://' + edit.GetValuePattern().Value else: print("sys.platform={platform} is not supported.".format( platform=sys.platform)) print(sys.version) return _active_window_name
def vote(url, count): '''投票''' global nextVoteIndex global voteIngFlag global handleDict log('vote() begin...') voteIngFlag = True console = uiautomation.GetConsoleWindow() while count > 0: if nextVoteIndex >= nextHandleKey: nextVoteIndex = 0 if nextVoteIndex not in handleDict.keys(): nextVoteIndex += 1 continue window = uiautomation.ControlFromHandle(handleDict[nextVoteIndex]) if window == None: log('Error: window not exist ' + str(nextVoteIndex) + ' ' + str(handleDict[nextVoteIndex]) + ', so pop it') log('pop: ' + str(nextVoteIndex) + ' ' + str(handleDict[nextVoteIndex])) handleDict.pop(nextVoteIndex) nextVoteIndex += 1 else: window.ShowWindow(uiautomation.ShowWindow.Maximize) window.SetActive() # # 点击搜索 # uiautomation.Win32API.MouseClick(126, 24) # # 输入“文件传输助手” # window.SendKeys(u'文件传输助手') # # 点击联系人 # uiautomation.Win32API.MouseClick(147, 88) # 直接点击第一个联系人 uiautomation.Win32API.MouseClick(136, 73) log('click') # 输入url window.SendKeys(40 * '{Ctrl}{Enter}' + 4 * (url + ' ') + '{Enter}', interval=0) log('click1') # time.sleep(0.5) # 点击输入框的上面一行文字(要求刚输入的文字就贴在输入框上方),弹出webview或浏览器 uiautomation.Win32API.MouseClick(1661, 817) log('click2') time.sleep(0.5) # 做投票动作 # dovote3(window) # TODO 等待并截图,或者判断是否成功 count -= 1 # 窗口放到最后 window.SendKeys('{ALT}{ESC}') log('vote end window: ' + str(handleDict[nextVoteIndex])) nextVoteIndex += 1 console.SetActive() voteIngFlag = False log('vote() end...')
def getBrowserUrl(current_window_id): ''' Returns the domain url of the active window on the browser app ''' browserControl = auto.ControlFromHandle(current_window_id) edit = browserControl.EditControl() url = edit.GetValuePattern().Value url_string = url.split('/') if len(url_string) > 2: return (url_string[2]) elif len(url_string) == 2: return (url_string[1]) else: return (url_string[0])
def train(): log('>>>> train() begin...') console = uiautomation.GetConsoleWindow() index = 0 while True: if voteIngFlag: time.sleep(600) continue if index >= nextHandleKey: index = 0 if index not in handleDict.keys(): index += 1 continue window = uiautomation.ControlFromHandle(handleDict[index]) if window == None: log('Error: window not exist ' + str(index) + ' ' + str(handleDict[index]) + ', so pop it') handleDict.pop(index) log('pop: ' + str(index) + ' ' + str(curHandle)) index += 1 else: window.ShowWindow(uiautomation.ShowWindow.Maximize) window.SetActive() log('train begin: ' + str(handleDict[index]) + ' ' + str(index)) # 直接点击第1个联系人 time.sleep(3) uiautomation.Win32API.MouseClick(136, 73) # window.SendKeys(time.strftime('%Y-%m-%d %H:%M:%S')+' 你好想是个A风筝的线条固阳A.{Enter}') # 直接点击第2个联系人 time.sleep(3) uiautomation.Win32API.MouseClick(136, 129) # window.SendKeys(time.strftime('%Y-%m-%d %H:%M:%S')+' 你好想是个B风筝的线条固阳B.{Enter}') # 直接点击第3个联系人 time.sleep(3) uiautomation.Win32API.MouseClick(136, 181) # window.SendKeys(time.strftime('%Y-%m-%d %H:%M:%S')+' 你好想是个C风筝的线条固阳C.{Enter}') # 直接点击第4个联系人 time.sleep(3) uiautomation.Win32API.MouseClick(136, 245) # window.SendKeys(time.strftime('%Y-%m-%d %H:%M:%S')+' 你好想是个D风筝的线条固阳D.{Enter}') # 直接点击第5个联系人 time.sleep(3) uiautomation.Win32API.MouseClick(136, 317) # window.SendKeys(time.strftime('%Y-%m-%d %H:%M:%S')+' 你好想是个E风筝的线条固阳E.{Enter}') # 收尾窗口放到最后 window.SendKeys('{ALT}{ESC}') log('train end ' + str(handleDict[index]) + ' \n') index += 1 time.sleep(300) #1776 console.SetActive() log('>>>> train() end...')
def ConnectWindow(self, selector): # 目前来说,如下处理,以后添加更多的参数后需修改代码逻辑 argunums = 0 if 'handle' in selector: argunums += 1 if 'title' in selector: argunums += 1 if 'title_re' in selector: argunums += 1 if argunums == 0: raise ValueError("Expect handle or title, got none") elif argunums != 1: raise ValueError( "Too many arguments, only need handle or title or title_re") handleSetList = [] if 'title' in selector: handleSetList.append(self.ConnectWindowsByTitle(selector['title'])) if 'handle' in selector: handleSetList.append( self.ConnectWindowsByHandle(selector['handle'])) if "title_re" in selector: handleSetList.append( self.ConnectWindowsByTitleRe(selector['title_re'])) while -1 in handleSetList: handleSetList.remove(-1) # 有些参数没有提供会返回-1.把所有的-1去掉 if len(handleSetList) is 0: raise InvalidSurfaceException( selector, "Can't find any windows by the given parameter") handleSet = reduce(operator.__and__, handleSetList) # 提供了多个参数来确定唯一一个窗口,所以要做交集,取得唯一匹配的窗口 if len(handleSet) == 0: raise InvalidSurfaceException( selector, "Can't find any windows by the given parameter") elif len(handleSet) != 1: raise NonuniqueSurfaceException(selector) else: hn = handleSet.pop() # 取得那个唯一的窗口 self.root = UIAuto.ControlFromHandle(hn) if self.root is None: raise InvalidSurfaceException( selector, "Can't find any windows by the given parameter") self.SetForeground()
def get_chrome_url(): window = win32gui.GetForegroundWindow() chromeControl = auto.ControlFromHandle(window) edit = chromeControl.EditControl() try: url = edit.GetValuePattern().Value except (AttributeError, LookupError) as e: url = None print("Error trying to fetch url") print(e) if url is None: print("URL fetched is empty. Not logging this activity") return "" else: return get_site_from_url(url)
def get_chrome_url(self): if sys.platform in ['Windows', 'win32', 'cygwin']: window = win32gui.GetForegroundWindow() chromeControl = auto.ControlFromHandle(window) edit = chromeControl.EditControl() web = edit.GetValuePattern().Value if "cursos.canvas" in web: code = (web.split("/"))[2] self._class = self.param[code] elif sys.platform in ['Mac', 'darwin', 'os2', 'os2emx']: textOfMyScript = """tell app "google chrome" to get the url of the active tab of window 1""" s = NSAppleScript.initWithSource_( NSAppleScript.alloc(), textOfMyScript) results, err = s.executeAndReturnError_(None) return results.stringValue()
def get_chrome_url(): if sys.platform in ['Windows', 'win32', 'cygwin']: window = win32gui.GetForegroundWindow() chromeControl = auto.ControlFromHandle(window) edit = chromeControl.EditControl() return 'https://' + edit.GetValuePattern().Value elif sys.platform in ['Mac', 'darwin', 'os2', 'os2emx']: textOfMyScript = """tell app "google chrome" to get the url of the active tab of window 1""" s = NSAppleScript.initWithSource_( NSAppleScript.alloc(), textOfMyScript) results, err = s.executeAndReturnError_(None) return results.stringValue() else: print("sys.platform={platform} is not supported." .format(platform=sys.platform)) print(sys.version) return active_window_name
def script(duration): start_time = time.time() timeout = start_time + 60 * duration application = None app_dict = {} #Run Script for Desired Duration while time.time() < timeout: try: time.sleep(3) window = win32gui.GetForegroundWindow() win_name = win32gui.GetWindowText(window) #Handles Chrome Activities if "Google Chrome" in win_name: chromeControl = auto.ControlFromHandle(window) edit = chromeControl.DocumentControl() url = edit.GetValuePattern().Value base_url = re.search(r"https:\/\/(?:www\.)?([^\/]*)", url) if base_url: base_url = base_url.group(1) if application == base_url: continue #Update Time & Application Name elapsed_time = time.time() - start_time if application not in app_dict: app_dict[application] = elapsed_time app_dict[application] += elapsed_time application = base_url start_time = time.time() #Handles Other Applications else: if application == win_name: continue elapsed_time = time.time() - start_time if application not in app_dict: app_dict[application] = elapsed_time app_dict[application] += elapsed_time application = win_name start_time = time.time() except: continue #Finalizes Application Dictionary elapsed_time = time.time() - start_time if application not in app_dict: app_dict[application] = elapsed_time app_dict[application] += elapsed_time visualize(app_dict)
def color(): console = uiautomation.GetConsoleWindow() index = 0 while True: if voteIngFlag: log('voteIngFlag ...') time.sleep(6) continue if index >= nextHandleKey: break if index not in handleDict.keys(): index += 1 continue window = uiautomation.ControlFromHandle(handleDict[index]) if window == None: log('Error: window not exist ' + str(index) + ' ' + str(handleDict[index]) + ', so pop it') handleDict.pop(index) log('pop: ' + str(index) + ' ' + str(curHandle)) index += 1 else: window.ShowWindow(uiautomation.ShowWindow.Maximize) window.SetActive() log('train begin: ' + str(handleDict[index]) + ' ' + str(index)) # 直接点击第1个联系人 time.sleep(3) log('...: ') uiautomation.Win32API.MouseClick(136, 73) print(uiautomation.Win32API.GetPixelColor(136,73,handleDict[index])) # 直接点击第2个联系人 time.sleep(3) log('...: ') uiautomation.Win32API.MouseClick(136, 129) print(uiautomation.Win32API.GetPixelColor(136,129,handleDict[index])) # 收尾窗口放到最后 index += 1 window.SendKeys('{ALT}{ESC}') log('train end window ' + str(handleDict[index]) + ' \n') log('end\n') time.sleep(10) console.SetActive() log('>>>> train() end...')
def get_url(browser): # Refer - > https://gist.github.com/dongyuwei/a1c9d67e4af6bbbd999c if sys.platform in ['Windows', 'win32', 'cygwin']: window = win32gui.GetForegroundWindow() chromeControl = auto.ControlFromHandle(window) edit = chromeControl.EditControl() return 'https://' + edit.GetValuePattern().Value elif sys.platform in ['Mac', 'darwin', 'os2', 'os2emx']: if (browser == "chrome"): textOfMyScript = """tell application "Google Chrome" to return URL of active tab of front window""" elif (browser == "safari"): textOfMyScript = """tell application "Safari" to return URL of front document""" s = NSAppleScript.initWithSource_(NSAppleScript.alloc(), textOfMyScript) results, err = s.executeAndReturnError_(None) return results.stringValue() else: print("sys.platform={platform} is not supported.".format( platform=sys.platform)) print(sys.version) return _active_window_name
def GetControlFromPid(pid, ignore_error=False): def get_hwnds(pid): """return a list of window handlers based on it process id""" def callback(hwnd, hwnds): if win32gui.IsWindowVisible(hwnd) and win32gui.IsWindowEnabled(hwnd): _, found_pid = win32process.GetWindowThreadProcessId(hwnd) if found_pid == pid: hwnds.append(hwnd) return True hwnds = [] win32gui.EnumWindows(callback, hwnds) if not hwnds: raise LookupError(f"Unable to find control with pid {pid}") return hwnds[0] try: return uiautomation.ControlFromHandle(get_hwnds(pid)) except LookupError: if not ignore_error: raise RuntimeError(f"Unable to find control with pid {pid}") from None else: return None
def SetText(self, id, val2): control = UIAuto.ControlFromHandle(id) if not control or not isinstance(val2, string_types): raise UnableToSetAttributeException("text", control) else: control.SetValue(val2)
def get_browser_tab_url(self): window = gui.GetForegroundWindow() chromeControl = auto.ControlFromHandle(window) edit = chromeControl.EditControl() return edit.GetValuePattern().Value
def hide(stopEvent: Event, handles: List[int]): #_uiobj = auto.UIAutomationInitializerInThread() # Hide doesn't call any COM methods, so it doesn't need an UIAutomationInitializerInThread for handle in handles: win = auto.ControlFromHandle(handle) win.Hide(0)
def get_browser_url(): window = win32gui.GetForegroundWindow() chromeControl = auto.ControlFromHandle(window) edit = chromeControl.EditControl() return 'https://' + edit.GetValuePattern().Value
def get_chrome_url(): window = w.GetForegroundWindow() chromeControl = auto.ControlFromHandle(window) edit = chromeControl.EditControl() return "https://" + edit.GetValuePattern().Value
def hide(stopEvent: Event, handles: List[int]): with auto.UIAutomationInitializerInThread(): for handle in handles: win = auto.ControlFromHandle(handle) win.Hide(0)
def url_formatter(): window = win32gui.GetForegroundWindow() chrome = uiautomation.ControlFromHandle(window) return chrome.EditControl().GetValuePattern().Value.split("/")[0]