def startMonitoring(lists): record = [-1] * 5 active = GetForegroundWindow() threadID, processID = GetWindowThreadProcessId(active) procname = Process(processID) prevStamp = datetime.datetime.now() f = open("processTime.txt", "w") while 1: print("checking...") print(active) print(GetForegroundWindow()) print(procname.name()) if active != GetForegroundWindow(): for list in lists: if procname.name() in list: if record[lists.index(list)] == -1: record[lists.index(list)] = datetime.datetime.now() - prevStamp else: record[lists.index(list)] += datetime.datetime.now() - prevStamp print(procname.name() + " "+ str(record[lists.index(list)])+ "\n") active = GetForegroundWindow() threadID, processID = GetWindowThreadProcessId(active) procname = Process(processID) prevStamp = datetime.datetime.now() sleep(2)
def callback(hwnd, hwnds): if win32gui.IsWindowVisible(hwnd) and win32gui.IsWindowEnabled( hwnd): _, found_pid = GetWindowThreadProcessId(hwnd) if found_pid == pid: hwnds.append(hwnd) return True
def get_active_window_win(self): from win32gui import GetWindowText, GetForegroundWindow from win32process import GetWindowThreadProcessId hwnd = GetForegroundWindow() tid, pid = GetWindowThreadProcessId(hwnd) capt = GetWindowText(hwnd) return (pid, capt)
def BringHwndToFront(hWnd, invalidate=True): if hWnd is None: return hWnd = GetAncestor(hWnd, GA_ROOT) if not IsWindow(hWnd): return # If the window is in a minimized state, restore now if IsIconic(hWnd): ShowWindow(hWnd, SW_RESTORE) BringWindowToTop(hWnd) UpdateWindow(hWnd) # Check to see if we are the foreground thread foregroundHwnd = GetForegroundWindow() foregroundThreadID = GetWindowThreadProcessId(foregroundHwnd, None) ourThreadID = GetCurrentThreadId() # If not, attach our thread's 'input' to the foreground thread's if foregroundThreadID != ourThreadID: AttachThreadInput(foregroundThreadID, ourThreadID, True) ShowWindow(hWnd, SW_SHOWNA) BringWindowToTop(hWnd) # Force our window to redraw if invalidate: InvalidateRect(hWnd, None, True) if foregroundThreadID != ourThreadID: AttachThreadInput(foregroundThreadID, ourThreadID, False)
def get_process_id_by_window_title(window_title) -> int: """ Get a window title and return its process ID. """ hwnd = FindWindow(None, window_title) return GetWindowThreadProcessId(hwnd)[1] if hwnd else 0
def memoread(NAME, ADDR): ReadProcessMemory = ctypes.windll.kernel32.ReadProcessMemory PROCESS_ALL_ACCESS = 0x1F0FFF while 1: HWND = FindWindow(None, NAME) if HWND == 0: continue else: break print("%s HWND: %i" % (NAME, HWND)) PID = GetWindowThreadProcessId(HWND)[1] print("%s PID: %i" % (NAME, PID)) try: HANDLE = OpenProcess(PROCESS_ALL_ACCESS, 0, PID) except Exception as error: print("OpenProcess error:", error) exit(0) print("%s HANDLE: %i" % (NAME, HANDLE.handle)) buffer_size = 256 buffer = ctypes.create_string_buffer(buffer_size) ReadProcessMemory(HANDLE.handle, ADDR, buffer, buffer_size, 0) return buffer.raw
def callback(hwnd, hwnds): # in order to minimize it to the SystemTray later if IsWindowVisible(hwnd) and IsWindowEnabled(hwnd): _, found_pid = GetWindowThreadProcessId(hwnd) if found_pid == pid: hwnds.append(hwnd) return True
def _get_active_window_on_nt(self) -> Tuple[Optional[str], ...]: """Returns details of the active window on windows platform""" # See https://stackoverflow.com/a/47936739 for reference code. # pyright: reportUndefinedVariable=false window, program = GetForegroundWindow(), None pid = GetWindowThreadProcessId(window)[-1] # We are considering only one active instance of a process. # Even if the parent process spawns multiple child processes # this check ensures that we do not record instances of a # process that were not interacted by the user. if psutil.pid.exists(pid): window = GetWindowText(window) # Skip `Task Switching` program and other program # switching overlays that are invoked with `Alt + Tab`. window = window if window != "Task Switching" else None path = psutil.Process(pid).exe() # See https://stackoverflow.com/a/31119785 for using # windows resource table for parsing program name. try: lang, page = _info(path, "\\VarFileInfo\\Translation")[0] addr = "%04X%04X" % (lang, page) file = u"\\StringFileInfo\\{}\\FileDescription".format(addr) program = _info(path, file) except NameError: self.log.error(f"{self._name} could not resolve program name.") window = None program = None return window, program
def get_activity(): # Gets process and window names every second, appends to session_log when change is detected. active_time = 0 try: active_process_name = Process( GetWindowThreadProcessId(GetForegroundWindow())[-1]).name() except (NoSuchProcess, ValueError): active_process_name = 'NoSuchProcess' active_window_name = GetWindowText(GetForegroundWindow()) or 'NoSuchWindow' session_log, output_db = {}, {} datetime_start = str(datetime.datetime.now()).split() output_db.update({ 'start_date': datetime_start[0], 'start_time': datetime_start[1] }) while True: try: root.update() except TclError: pass start = time.time() activity_now = (active_process_name, active_window_name) try: active_process_name = Process( GetWindowThreadProcessId(GetForegroundWindow())[-1]).name() except (NoSuchProcess, ValueError): active_process_name = 'NoSuchProcess' active_window_name = GetWindowText( GetForegroundWindow()) or 'NoSuchWindow' if activity_now == (active_process_name, active_window_name): active_time += 1 else: if activity_now not in session_log.keys(): session_log.update({activity_now: active_time + 1}) elif activity_now in session_log.keys(): session_log[activity_now] += active_time + 1 active_time = 0 time.sleep(1 - (time.time() - start)) if activity_now == ('python.exe', 'Stopping Logging'): break datetime_end = str(datetime.datetime.now()).split() output_db.update({'activity': list(session_log.items())}) output_db.update({ 'end_date': datetime_end[0], 'end_time': datetime_end[1] }) return output_db
def initVars(self): self.active = GetForegroundWindow() self.threadID, processID = GetWindowThreadProcessId(self.active) self.prevStamp = datetime.datetime.now() try: self.procName = Process(processID) except NoSuchProcess: pass
def get_threadname(HWND): pprocess = GetWindowThreadProcessId(HWND) try: p = psutil.Process(pprocess[1]) except Exception as e: return 0 #print(p.name()) return p.as_dict(attrs=['pid', 'name'])
def callback(hwnd, hwnds_): if IsWindowEnabled(hwnd): _, found_pid = GetWindowThreadProcessId(hwnd) if found_pid == pid: hwnds_.append(hwnd) return True
def get_pid(hwnd, ignored): if not found and IsWindow(hwnd) and IsWindowEnabled( hwnd) and IsWindowVisible(hwnd): _hwnd, _pid = GetWindowThreadProcessId(hwnd) if check_is_mc(hwnd, _pid): if debug: print( "[DEBUG]find_mc->get_pid: _hwnd = %s | hwnd = %s | _pid = %s" % (_hwnd, hwnd, _pid))
def PyGetWindowThreadProcessId(hWnd): """ Retrieves the identifier of the thread and process that created the specified window. int threadId, int processId = GetWindowThreadProcessId(hWnd) """ dwProcessId = DWORD() threadId = GetWindowThreadProcessId(hWnd, byref(dwProcessId)) return threadId, dwProcessId.value
def get_pid(hwnd, ignored): if IsWindow(hwnd) and IsWindowEnabled(hwnd) and IsWindowVisible(hwnd): pid = GetWindowThreadProcessId(hwnd)[1] if "dwm" in psutil.Process(pid).name() and "minecraft".upper( ) in str(GetWindowText(hwnd)).upper(): if debug: print("[DEBUG]find_mc_dwm(): pid = %s | hwnd = %s" % (pid, hwnd)) global dmw dmw = hwnd
def on_enumerate(_window, params): global windows_in_fs_1 global windows_in_fs_2 if is_in_full_screen_1(_window) and not blacklisted(_window): windows_in_fs_1 = windows_in_fs_1 + 1 print("FS 1: {0} {1} Visible: {2}", GetWindowText(_window), GetWindowThreadProcessId(_window)[1], IsWindowVisible(_window)) if is_in_full_screen_2(_window) and not blacklisted(_window): windows_in_fs_2 = windows_in_fs_2 + 1
def get_text_from_focused_control(): try: activeWinPtr = GetForegroundWindow() activeThreadId, _ = GetWindowThreadProcessId(activeWinPtr) currentThreadId = GetCurrentThreadId() if activeThreadId != currentThreadId: AttachThreadInput(activeThreadId, currentThreadId, True) activeCtrlId = GetFocus() return GetText(activeCtrlId) except Exception: print("HUHU") return ""
def get_current_foreground_app_process_name(self): try: hwnd = GetForegroundWindow() pid = GetWindowThreadProcessId(hwnd) handle = OpenProcess( PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, False, pid[1], ) path = GetModuleFileNameEx(handle, 0) name = path.split("\\")[-1] return name except: return None
def checkforbrowser(): ''' Check whether the input is mozilla, and returns True if so. ''' current_window_id = GetForegroundWindow() pid = GetWindowThreadProcessId(current_window_id) application_name = Process(pid[-1]).name() application_name = application_name.replace(".exe", "") if ((application_name == 'firefox') or (application_name == 'chrome')) or (application_name == 'iexplore'): return True else: return False
def get_threadname(HWND): import psutil from win32process import GetWindowThreadProcessId pprocess = GetWindowThreadProcessId(HWND) try: p = psutil.Process(pprocess[1]) except: p = [] return p
def openpB(self, processName=None, windowTitle=None): # open a process / plan B ID = win32gui.FindWindow(processName, windowTitle) if not ID: return 0 # no task man window open global ctypes, wintypes from win32con import PROCESS_ALL_ACCESS from win32process import GetWindowThreadProcessId from ctypes import wintypes import ctypes, pywinauto PROCESS_VM_OPERATION = pywinauto.win32defines.PROCESS_VM_OPERATION PROCESS_VM_READ = pywinauto.win32defines.PROCESS_VM_READ PROCESS_VM_WRITE = pywinauto.win32defines.PROCESS_VM_WRITE PROCESS_QUERY_INFORMATION = pywinauto.win32defines.PROCESS_QUERY_INFORMATION try: # create Handle to process. # ID = win32gui.FindWindow ( processName , windowTitle ) TID = GetWindowThreadProcessId(ID)[-1] # If the function succeeds # the return value is an open handle to the specified process. Handle = ctypes.windll.kernel32.OpenProcess (\ PROCESS_VM_OPERATION|PROCESS_VM_READ|PROCESS_VM_WRITE |PROCESS_QUERY_INFORMATION,# This access right is checked against the # security descriptor for the process. False, # If this value is TRUE, processes created by this process will inherit the handle. TID ) # The identifier of the local process to be opened. return Handle except Exception, error: print error
def get_keyboard_language(): languages = {'0x409': 'English', '0x419': 'Russian'} # Get the current active window handle handle = GetForegroundWindow() # Get the thread id from that window handle threadid, processid = GetWindowThreadProcessId(handle) # Get the keyboard layout id from the threadid layout_id = GetKeyboardLayout(threadid) # Extract the keyboard language id from the keyboard layout id language_id = layout_id & (2**16 - 1) # Convert the keyboard language id from decimal to hexadecimal language_id_hex = hex(language_id) # Check if the hex value is in the dictionary. if language_id_hex in languages.keys(): return languages[language_id_hex] else: # Return language id hexadecimal value if not found. return str(language_id_hex)
def __init__(self, hwnd): # 这里我们在类创建的时候,接受一个窗口句柄,然后通过窗口句柄让类自己去创建相应的进程 self.ntdll = WinDLL("ntdll.dll") pid = GetWindowThreadProcessId(hwnd) self.hProcess = OpenProcess(PROCESS_VM_READ | PROCESS_QUERY_INFORMATION | PROCESS_VM_WRITE, False, pid[1]) """ 这个函数有三个参数,第一个参数是你需要的权限,我不是很喜欢这种直接获取全部权限,因为有的时候权限太高并不是好事情
def GetProcessIdByWindow(strWindowName, strWindowClass=None): return GetWindowThreadProcessId( win32ui.FindWindow(strWindowClass, strWindowName).GetSafeHwnd())[1]
def get_pid(self): """gets process id of command prompt on foreground""" window = GetForegroundWindow() return GetWindowThreadProcessId(window)[1]
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]) # Defining dictionary for storing values app_dictionary = {} start = time.time() last_window_id = GetForegroundWindow() pid = GetWindowThreadProcessId(last_window_id) application_name = Process(pid[-1]).name() application_name = application_name.replace(".exe", "") print(application_name) while True: current_window_id = GetForegroundWindow() if (current_window_id != last_window_id) & (len( GetWindowText(current_window_id)) != 0): end = time.time() duration, time_tuple = printTime(end - start) #print(current_window_id) #print(len(GetWindowText(current_window_id))) if round(end - start) != 0: print(duration)
def KillSelf(self): _, PID = GetWindowThreadProcessId(self.mHwnd) p = psutil.Process(PID) p.terminate()
def readactivityfile(activityfile): ''' Read the activity file into the dictionary ''' with open(activityfile, "r") as f: data = json.load(f) return data def writeactivityfile(activityfile, data): ''' Write the activity dictionary to activity file ''' with open(activityfile, "w+") as f: json.dump(data, f, indent=3, sort_keys=True) ## Main ## ## Get the current process name curWin = ((Process(GetWindowThreadProcessId( GetForegroundWindow())[-1]).name()).split('.')[0]).lower() # Set the start time stime = datetime.now().time().strftime('%H:%M:%S') # Initialize dictionary and the json output file activitydata = dict() activityfile = os.path.dirname(os.path.realpath(__file__)) + '\\activity.json' # Check if json file exists. If yes, load the file into dictionary if (os.path.exists(activityfile)): activitydata = readactivityfile(activityfile) # Continuously run the app while (True): try: # Get the name of curent active window
def callback(hwnd, hwnds): if IsWindowVisible(hwnd): _, result = GetWindowThreadProcessId(hwnd) if result == pid: hwnds.append(hwnd) return True
def GetWindowProcessName(hWnd): dwProcessId = DWORD() GetWindowThreadProcessId(hWnd, byref(dwProcessId)) return GetProcessName(dwProcessId.value)