def close_top_window(self, hwnd, _): """Close all top-level windows""" keep_titles = ['Start'] keep_classes = ['ConsoleWindowClass', 'Windows.UI.Core.CoreWindow'] keep_exes = ['explorer.exe', 'cmd.exe', 'teamviewer.exe'] try: import win32api import win32con import win32event import win32gui import win32process import psutil if win32gui.IsWindowVisible(hwnd): window_title = win32gui.GetWindowText(hwnd) window_class = win32gui.GetClassName(hwnd) _, proccess_id = win32process.GetWindowThreadProcessId(hwnd) exe = os.path.basename( psutil.Process(proccess_id).exe()).lower() if len(window_title) and \ window_title not in keep_titles and \ window_class not in keep_classes and \ exe not in keep_exes: placement = win32gui.GetWindowPlacement(hwnd) left, top, right, bottom = win32gui.GetWindowRect(hwnd) width = abs(right - left) height = abs(bottom - top) if width > 0 and height > 0 and \ top >= 0 and left >= 0 and \ placement[1] != win32con.SW_SHOWMINIMIZED and \ placement[1] != win32con.SW_MINIMIZE and \ placement[1] != win32con.SW_FORCEMINIMIZE: logging.debug( "Closing Window: %s (%s) : %d,%d %dx%d : %d - %s", window_title, window_class, left, top, width, height, placement[1], exe) handle = win32api.OpenProcess( win32con.PROCESS_TERMINATE | win32con.SYNCHRONIZE | win32con.PROCESS_QUERY_INFORMATION, 0, proccess_id) win32gui.PostMessage(hwnd, win32con.WM_CLOSE, 0, 0) if handle: result = win32event.WaitForSingleObject( handle, 10000) if result == win32event.WAIT_TIMEOUT: logging.debug( "Terminating process for: %s (%s)", window_title, window_class) win32api.TerminateProcess(handle, 0) win32api.CloseHandle(handle) except Exception: pass
def get_app_name(hwnd): """Get application filename given hwnd.""" exe = None try: _, pid = win32process.GetWindowThreadProcessId(hwnd) for p in c.query( 'SELECT Name FROM Win32_Process WHERE ProcessId = %s' % str(pid)): exe = p.Name break except: return None return exe
def do_action(self, action): print("do action\n") program_name = "general" # Get active window try: pid = win32process.GetWindowThreadProcessId( win32gui.GetForegroundWindow() ) #This produces a list of PIDs active window relates to program_name = psutil.Process(pid[-1]).exe() except Exception as e: print(str(e)) #print("Active Program: " + program_name + "\n") operation = "" key_in_dict = "" for key in self.config_DB.keys(): if key.split("~")[1] == program_name: key_in_dict = key break elif key.split("~")[0] == "Default": key_in_dict = key if key_in_dict != "": # Found action for the program if action in self.config_DB[key_in_dict].keys(): operation = self.config_DB[key_in_dict][action] #operation = operation.lower() print("Key to press: " + str(operation) + "\n") try: #press the key if len(operation.split("+")) > 1 and len(operation) > 1: if len(operation.split("+")) == 2: pyautogui.hotkey( operation.split("+")[0], operation.split("+")[1]) else: pyautogui.hotkey( operation.split("+")[0], operation.split("+")[1], operation.split("+")[2]) else: if not (operation.isalpha() and len(operation) == 1): operation = operation.lower() pyautogui.press(operation) print("pressed\n") except Exception as e: print(str(e)) else: print("No definition has been setted\n")
def find_app_name(): global exclude_apps substitute_names = { 'Msedge': 'Edge (Chromium)', 'Picasaphotoviewer': 'Picasa', 'Pycharm64': 'PyCharm', 'Startmenuexperiencehost': 'Explorer' } browsers = [ 'chrome.exe', 'firefox.exe', 'msedge.exe', 'iexplore.exe', 'opera.exe' ] window_object = win32gui.GetForegroundWindow() window_original = win32gui.GetWindowText(window_object) window_original = window_original.replace("'", "") window_original = window_original.replace('"', '') try: thread_pid, process_pid = win32process.GetWindowThreadProcessId( window_object) process = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, False, process_pid) process_name = win32process.GetModuleFileNameEx(process, 0) process_name = process_name.split("\\")[-1].lower() app_name = process_name.split(".exe")[0].title() except Exception as e: app_name = window_original.split("- ")[-1].title() process_name = (app_name.replace(" ", "_") + ".exe").lower() # app_name = "Task Manager" if process_name == "applicationframehost.exe": app_name = window_original.split("- ")[-1].title() if app_name in substitute_names: app_name = substitute_names[app_name] if process_name.lower() in exclude_apps: process_name = "Excluded App" app_name = "Excluded App" window_original = "Excluded App" if process_name in browsers: browser_flag = 1 else: browser_flag = 0 return app_name, process_name, window_original, browser_flag
def enum_windows_process(window_handle, process_pid): (other_thread_id, other_process_id) = win32process.GetWindowThreadProcessId(window_handle) if other_process_id != process_pid: return text = win32gui.GetWindowText(window_handle) if not text: return window_style = win32api.GetWindowLong(window_handle, win32con.GWL_STYLE) if window_style & win32con.WS_VISIBLE: titles.append(text)
def get_active_app_name(self): try: hwnd = win32gui.GetForegroundWindow() _, pid = win32process.GetWindowThreadProcessId(hwnd) for p in self.wmi.query( 'SELECT Name FROM Win32_Process WHERE ProcessId = %s' % str(pid)): exe = p.Name break except: return None else: # noinspection PyUnboundLocalVariable return exe
def winEnumHandler(hwnd, ctx): if win32gui.IsWindowVisible(hwnd): pid = win32process.GetWindowThreadProcessId(hwnd) # win32gui.GetWindowText(hwnd) ##Pencere adını veriyor. # ##Spotify penceresinin adında da dinlediğimiz şarkı yazıyor. # psutil.Process(pid[1]).name() ##Pencerenin hangi programa ait olduğunu veriyor. program = dict() program["title_name"] = win32gui.GetWindowText(hwnd) program["exe_name"] = psutil.Process(pid[1]).name() programs.append( program ) # Bütün programları sözlük şeklinde programs listesine ekliyor.
def win_get_app_name(hwnd): """Get application name given hwnd.""" c = wmi.WMI() try: _, pid = win32process.GetWindowThreadProcessId(hwnd) for p in c.query( 'SELECT Name FROM Win32_Process WHERE ProcessId = %s' % str(pid)): exe = p.Name.rsplit('.', 1)[0] break except: return 'unknown' else: return exe
def set_foreground_window(hwnd): fwnd = win32gui.GetForegroundWindow() if fwnd == hwnd: return if fwnd == 0: try: win32gui.SetForegroundWindow(hwnd) return except win32api.error: return ftid, _ = win32process.GetWindowThreadProcessId(fwnd) wtid, _ = win32process.GetWindowThreadProcessId(hwnd) ctypes.windll.user32.AttachThreadInput(wtid, ftid, True) st = time.time() while (time.time() - st) < 5: if win32gui.GetForegroundWindow() == hwnd: break ctypes.windll.user32.SetForegroundWindow(hwnd) time.sleep(0.5) ctypes.windll.user32.AttachThreadInput(wtid, ftid, False)
def winEnumHandler(hwnd, _): global focused_window global spotify_install_path global block if IsWindowVisible(hwnd): wintext = GetWindowText(hwnd) _, pid = win32process.GetWindowThreadProcessId(hwnd) if wintext != None and wintext != "" and wintext != " ": if not block: # and (wintext == "Spotify Free" or wintext == "Advertisement"): # if wintext == "Spotify Free" or wintext == "Advertisement": adcheck() song_name(wintext, pid)
def get_process_times(): try: current_app = psutil.Process( win32process.GetWindowThreadProcessId( GetForegroundWindow())[1]).name().replace(".exe", "") except: print('error getting process') return process_time if current_app not in process_time.keys(): process_time[current_app] = 0 process_time[current_app] += anim_interval print(process_time) return process_time
def get_process_id_by_window(class_: Optional[str], title: Optional[str]) -> Optional[int]: """Get process id by windows class and/or title. If class or title is None, only search by another parameter. :param class_: Window class :param title: Window title :return: process id if window found, otherwise None """ window = win32gui.FindWindow(class_, title) if not window: return None (_, pid) = win32process.GetWindowThreadProcessId(window) return pid
def press_code_on_ths(hwnd_ths, code='002531'): win32gui.PostMessage(hwnd_ths, win32con.WM_KEYDOWN, ord('6') & 0xFF, 0) win32gui.PostMessage(hwnd_ths, win32con.WM_KEYUP, ord('6') & 0xFF, 0) time.sleep(0.3) win32gui.SetForegroundWindow(hwnd_ths) self_thread_id = win32api.GetCurrentThreadId() fore_thread_id = win32process.GetWindowThreadProcessId(hwnd_ths) win32process.AttachThreadInput(fore_thread_id[0], self_thread_id, True) obj_wnd = win32gui.GetFocus() win32gui.SendMessage(obj_wnd, win32con.WM_SETTEXT, 0, code) win32gui.PostMessage(obj_wnd, win32con.WM_KEYDOWN, win32con.VK_RETURN, 0) win32gui.PostMessage(obj_wnd, win32con.WM_KEYUP, win32con.VK_RETURN, 0) win32process.AttachThreadInput(fore_thread_id[0], self_thread_id, False) return True
def open_file_in_picoCAD_window(window_hwnd, filepath): if os.path.exists(filepath): # ft = FILETIME(filepath) # wp = WPARAM(ft) # win32gui.SendMessage(window_hwnd, win32con.WM_DROPFILES, wp, 0) # this is following https://www.programmersought.com/article/34354276878/ filepath = bytes( filepath + "\0\0", encoding="GBK" ) # The end of the file path must be followed by two 0s, in order to support Chinese encoding GBK # Use ctypes struct to simulate DROPFILES structure. #The first parameter 0x14 means that the file path in the memory area of the message body starts from the first few bytes, #That is the corresponding pFiles parameter of DROPFILES, the parameters behind are similar to the principle, #I defined the point where the mouse was released at the (10,10) position of the window, so it is 0x0A,0x0A DropFilesInfo = struct.pack("iiiii" + str(len(filepath)) + "s", *[0x14, 0x0A, 0x0A, 00, 00, filepath]) # Create a buffer from the structure, which is equivalent to obtaining the address of the structure, #Then see the entire structure as a memory area, you can also use ctypes.addressof(DropFilesInfo) to get the address value directly s_buff = ctypes.create_string_buffer(DropFilesInfo) pid = ctypes.c_uint(0) pid = ctypes.wintypes.UINT() pid = ctypes.c_ulong(0) # GetWindowThreadProcessId(window_hwnd, ctypes.addressof(pid)) #Get the process ID, so as to subsequently apply for memory in the process address space. address = ctypes.addressof(pid) # print(address) # thread_id = GetWindowThreadProcessId(window_hwnd, address) #Get the process ID, so as to subsequently apply for memory in the process address space. thread_id, pid = win32process.GetWindowThreadProcessId(window_hwnd) # print("pid:%x" % pid, "Thread id:", thread_id) hProcHnd = OpenProcess( PROCESS_ALL_ACCESS, False, pid) #Open the process and obtain the process handle. # print("open Process:%x" % hProcHnd) pMem = VirtualAllocEx( hProcHnd, 0, len(DropFilesInfo), MEM_COMMIT, PAGE_READWRITE ) # In the target process, apply for a memory area that can accommodate DROPFILES and file paths WriteProcessMemory(hProcHnd, pMem, s_buff, len(DropFilesInfo), None) # Write the message body win32gui.SendMessage( window_hwnd, win32con.WM_DROPFILES, pMem ) # Simulate sending drag messages to the corresponding process. VirtualFreeEx( hProcHnd, pMem, 0, win32con.MEM_RELEASE ) #After use up, the corresponding memory area should be released to prevent memory leakage.
def telaLol(self): w = win32gui w.GetWindowText(w.GetForegroundWindow()) pid = win32process.GetWindowThreadProcessId(w.GetForegroundWindow()) nome = "" try: nome = psutil.Process(pid[-1]).as_dict(attrs=['name']) except: print("não achei o nome") print(nome['name']) if nome['name'].lower() == "league of legends.exe": return True else: return False
def get_hwnds_for_hwnd (self,hw = None): if hw == None: hw = self._handle def callback (hwnd, hwnds): if win32gui.IsWindowVisible (hwnd): _, found_pid = win32process.GetWindowThreadProcessId (hwnd) if found_pid == pid: hwnds.append (hwnd) return True _, pid = win32process.GetWindowThreadProcessId (hw) hwnds = [] win32gui.EnumWindows (callback, hwnds) return hwnds
def winEnumHandler(hwnd, ctx): #if win32gui.IsWindowVisible( hwnd ): print(hex(hwnd), win32gui.GetWindowText(hwnd)) for a in usernames: if a in win32gui.GetWindowText(hwnd): print("Found " + a + " window located at " + str(hex(hwnd))) threadid, pid = win32process.GetWindowThreadProcessId(hwnd) print("Thread ID: " + str(threadid)) print("Process ID: " + str(pid)) for p in c.query( 'SELECT Name FROM Win32_Process WHERE ProcessId = %s' % str(pid)): exe = p.Name print("Process Name: " + exe)
def setAppWindowForeground(Appname, windowsize=3): # 让特定程序获得焦点 hForeWnd = win32gui.GetForegroundWindow() dwCurID = win32api.GetCurrentThreadId() dwForeID = win32process.GetWindowThreadProcessId(hForeWnd) windowHandle = win32gui.FindWindow(0, Appname) if hForeWnd != 0 and dwCurID != dwForeID[0]: win32process.AttachThreadInput(dwCurID, dwForeID[0], True) # 参数解释https://msdn.microsoft.com/en-us/library/windows/desktop/ms633548(v=vs.85).aspx win32gui.ShowWindow(windowHandle, windowsize) win32gui.SetWindowPos(windowHandle, -1, 0, 0, 0, 0, 0x0001 | 0x0002) win32gui.SetWindowPos(windowHandle, -2, 0, 0, 0, 0, 0x0001 | 0x0002) if hForeWnd != 0: win32gui.SetForegroundWindow(windowHandle)
def find_chrome_windows(hwnd, hwnds): try: _, win_pid = win32process.GetWindowThreadProcessId(hwnd) if (pid == win_pid and win32gui.IsWindowVisible(hwnd) and win32gui.IsWindowEnabled(hwnd) and win32gui.GetClassName(hwnd).lower().startswith(app_name)): hwnds.append(hwnd) except pywintypes.error, e: error_code = e[0] # Some windows may close after enumeration and before the calls above, # so ignore those. if error_code != winerror.ERROR_INVALID_WINDOW_HANDLE: raise
def get_pid(self): """ """ self.parent.ShowRas() window_text = 'HEC-RAS ' def enumHandler(hwnd, lParam): if window_text in win32gui.GetWindowText(hwnd): self.parent_window = hwnd return None win32gui.EnumWindows(enumHandler, None) _, pid = win32process.GetWindowThreadProcessId(self.parent_window) win32gui.ShowWindow(self.parent_window, win32con.SW_HIDE) self.parent_pid = pid
def get_pid_state(pid): state = None windows = [] def callback(hwnd, arg): windows.append(hwnd) win32gui.EnumWindows(callback, None) for hwnd in windows: if pid in win32process.GetWindowThreadProcessId(hwnd): placement = win32gui.GetWindowPlacement(hwnd) if placement[4][2] == 2560 and placement[4][3] == 1440: state = placement[1] return state
def find_windows(**kwargs): title = kwargs.get('title', None) class_name = kwargs.get('class_name', None) process = kwargs.get('process', None) parent = kwargs.get('parent', 0) top_level_only = kwargs.get('top_level_only', False) visible = kwargs.get('visible', None) enabled = kwargs.get('enabled', None) width = kwargs.get('width', None) encoding = kwargs.get('encoding', None) if isinstance(width, (int, float)): min_width = max_width = int(width) elif isinstance(width, (tuple, list)) and len(width) == 2: min_width, max_width = width min_width = math.floor(min_width) max_width = math.ceil(max_width) height = kwargs.get('height', None) if isinstance(height, (int, float)): min_height = max_height = int(height) elif isinstance(height, (tuple, list)) and len(height) == 2: min_height, max_height = height min_height = math.floor(min_height) max_height = math.ceil(max_height) tree_handles = get_tree_handles(parent, recursive=not top_level_only) handles = [] for handle in tree_handles: if isinstance(title, str): if encoding: if not GetWindowText(handle, encoding=encoding) == title: continue else: if not win32gui.GetWindowText(handle) == title: continue if process and not win32process.GetWindowThreadProcessId(handle)[-1] == process: continue if isinstance(class_name, str) and not win32gui.GetClassName(handle) == class_name: continue if visible is not None and not win32gui.IsWindowVisible(handle) == visible: continue if enabled is not None and not win32gui.IsWindowEnabled(handle) == enabled: continue if width or height: rect = win32gui.GetWindowRect(handle) if width and not min_width <= rect[2] - rect[0] <= max_width: continue if height and not min_height <= rect[3] - rect[1] <= max_height: continue handles.append(handle) return handles
def get_active_window(): try: pid = win32process.GetWindowThreadProcessId(win32gui.GetForegroundWindow()) return psutil.Process(pid[-1]).name() except psutil.NoSuchProcess: return None except psutil.AccessDenied: return None except AttributeError: return None except PermissionError: return None except ValueError: return None
def OnKeyboardEvent(event): global running global word global activity_frame hwnd = win32gui.FindWindow(None, event.WindowName) threadid, pid = win32process.GetWindowThreadProcessId(hwnd) handle = win32api.OpenProcess( win32con.PROCESS_QUERY_INFORMATION | win32con.PROCESS_VM_READ, False, pid) proc_name = win32process.GetModuleFileNameEx(handle, 0) if activity_frame.events == [] and activity_frame.window == {}: if 'x95' in event.WindowName: event.WindowName = "Unsaved Sublime Text File" activity_frame.window['name'] = event.WindowName # print(activity_frame.window['name']) activity_frame.window['process'] = proc_name if proc_name != activity_frame.window['process']: if word != '': activity_frame.events.append((word, time.time())) word = '' activity_frame.inactive = get_inactive_windows() activity_frame.network = get_active_networks() activity_frames.append(activity_frame) prettyprint(activity_frame) del activity_frame activity_frame = ActivityFrame([], {}, [], []) if event.Ascii == 27: if word != '': activity_frame.events.append((word, time.time())) activity_frame.inactive = get_inactive_windows() activity_frame.network = get_active_networks() activity_frames.append(activity_frame) prettyprint(activity_frame) # del activity_frame # activity_frame = ActivityFrame([],{}) # print(activity_frames[0].window) exit() elif event.Ascii == 32 or event.Ascii == 13 or event.Ascii == 9: if word != '': activity_frame.events.append((word, time.time())) word = '' else: word += event.Key return True
def check(self): try: tempWindowName = win32gui.GetWindowText( win32gui.GetForegroundWindow()) path = os.path.abspath( psutil.Process( win32process.GetWindowThreadProcessId( win32gui.GetForegroundWindow())[-1]).name()) except: path = self.path tempWindowName = self.tempWindowName if self.path != path or tempWindowName != self.tempWindowName: self.path = path self.tempWindowName = tempWindowName logging.info('Exe_file ' + self.path + '|' + tempWindowName)
def _get_window_info(self, hwnd, wildcard): """Get main window info. :param hwnd: window handle. :param wildcard: wildcard. """ if self.name == win32gui.GetWindowText(hwnd): try: self.parent_hwnd = hwnd self.parent_thread = win32process.GetWindowThreadProcessId( self.parent_hwnd) self.main_key_handle = win32gui.GetDlgItem(self.parent_hwnd, 0) self._update_rect_from_parent_hwnd() except pywintypes.error: pass
def getMyhwndByName(self, processname='【魔域】' ): #获取所有应用名字对应的获取窗口句柄列表,该句柄列表是通过时间排序的 try: hwnd = self.getHandle(processname) ph = {} hw = [] for h in hwnd: hreadID, pid = win32process.GetWindowThreadProcessId(h) ph[Process().getProCreatTime(pid)] = h for v in sorted(ph.keys()): #字典按进城时间排序 返回对应的值列表 hw.append(ph[v]) return hw except Exception as e: get_logger().info("PC_UI.UI.GetMyhwndByName:%s" % str(e))
def handle_cursor_move(self): ct = time.time() pos = QCursor.pos() if pos == self._cursor_pos: if ct - self._cursor_timestamp > 3: x, y = pos.x(), pos.y() hwnd = win32gui.WindowFromPoint((x, y)) _, found_pid = win32process.GetWindowThreadProcessId(hwnd) if found_pid != os.getpid(): self.__cursor_moved_timer.stop() self._update_window_item_prop(hwnd) self.select_window(hwnd) else: self._cursor_pos = pos self._cursor_timestamp = ct
def get_info(name): global hwnd global h_process hwnd = win32gui.FindWindow(None, name) if not hwnd: print("Find Window Failed! Please check the window name") return hid, pid = win32process.GetWindowThreadProcessId(hwnd) if not hid: print("Get Thread Id Failed! Please check the window name") return h_process = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, False, pid) if not h_process: print("Open Process Failed! Please check the privilege") return
def retornar_musica(): construir_l_final_de_janelas() for x in l_janelas_final: try: pid = win32process.GetWindowThreadProcessId(x[0]) handle = win32api.OpenProcess( win32con.PROCESS_QUERY_INFORMATION | win32con.PROCESS_VM_READ, False, pid[1]) proc_name = win32process.GetModuleFileNameEx(handle, 0) if 'Spotify' in proc_name: if '-' in x[1]: print(x[1]) return x[1] except: pass