Пример #1
0
def GetWindowTitleIfExists(config):
    __configContainsTitle__ = hasattr(config, "title_contains")
    for _title in pygetwindow.getAllTitles():
        if __configContainsTitle__:
            if len(_title) < 1: continue
            if config.title_contains.lower() in _title.lower():
                return _title
Пример #2
0
    def __init__(self):
        # find the handle for the window we want to capture
        titles = gw.getAllTitles()

        for t in titles:
            if "tx" in t.lower():
                self.hwnd = win32gui.FindWindow(None, t )
        if not self.hwnd:
            raise Exception('Window not found: ')

        # get the window size
        window_rect = win32gui.GetWindowRect(self.hwnd)
        self.w = window_rect[2] - window_rect[0]
        self.h = window_rect[3] - window_rect[1] 

        # account for the window border and titlebar and cut them off
        border_pixels = 8
        titlebar_pixels = 30
        self.w = self.w - (border_pixels * 2)
        self.h = self.h - titlebar_pixels - border_pixels
        self.cropped_x = border_pixels
        self.cropped_y = titlebar_pixels

        # set the cropped coordinates offset so we can translate screenshot
        # images into actual screen positions
        self.offset_x = window_rect[0] + self.cropped_x
        self.offset_y = window_rect[1] + self.cropped_y
 def showAllWindowTitles(self):
     # TODO linewrap!!!
     # TODO lable + add-button in frame -> in scrollbar
     try:
         self.allWindowNames_Window.lift(self)
     except:
         self.allWindowNames_Window = tk.Tk()
         self.allWindowNames_Window.title(
             "ApplicationTimeTracker - all window titles")
         S = Scrollbar(self.allWindowNames_Window)
         T = Text(self.allWindowNames_Window,
                  height=20,
                  width=80,
                  bg="lightgray")
         S.pack(side="right", fill="y")
         T.pack(side="left", fill="y")
         S.config(command=T.yview)
         T.config(yscrollcommand=S.set)
         text = ""
         for s in gw.getAllTitles():
             if len(s) >= 1:
                 text += s + "\n"
         T.insert(tk.END, text)
         T.config(state=tk.DISABLED)
         self.allWindowNames_Window.mainloop()
def game_image():
    """
    Obtains a screenshot of the current game state.
    :return: image of the game.
    :raise: if there is no game raise exceptions.GameNotFoundException()
    """
    time.sleep(3)
    current_window = gw.getActiveWindow()
    for title in gw.getAllTitles():
        if "Colonist: Play" in title:
            game_window = gw.getWindowsWithTitle(title)[0]
            game_window.minimize()
            game_window.maximize()
            time.sleep(0.4)

            # Screen capture
            image = ImageGrab.grab()
            image = np.array(image)

            # Removing boarder
            h, w, *_ = image.shape
            image = image[10:h - 10, 10: w - 10]

            image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
            game_window.minimize()
            current_window.maximize()
            return image
    else:
        raise exceptions.GameNotFoundException()
Пример #5
0
 def find_target_window_by_search_str(self):
     self.set_output_file()
     window_titles = gw.getAllTitles()
     while True:
         try:
             print(
                 f'Searching For Windows With The Title | {self.search_str}'
             )
             self.target_window = gw.getWindowsWithTitle([
                 _ for _ in window_titles
                 if self.search_str.lower() in _.lower()
             ][0])[0]
             self.window_found = True
             break
         except Exception as e:
             self.window_found = False
             if sg.PopupYesNo(
                     f'No Window With The Title {self.search_str} Was Found.\n\nSearch Again?',
                     keep_on_top=True,
                     no_titlebar=True) == 'Yes':
                 self.search_str = sg.PopupGetText('Enter The Search Word:',
                                                   keep_on_top=True,
                                                   no_titlebar=True,
                                                   default_text='project')
                 continue
             else:
                 raise (e)
Пример #6
0
    def __init__(self):
        self.os = platform.system()
        print(self.os)
        self.screen = pyautogui.size()

        # Region of interest
        self.roi = [-1, -1, -1, -1]

        if self.os == 'Windows':
            # import fails while using Linux
            import pygetwindow as gw

            window = gw.getAllTitles()
            for title in window:
                if "Super" in title or "Dolphin" in title:
                    window = title

            window = gw.getWindowsWithTitle(window)[0]
            window.moveTo(5, 5)
            window.resizeTo(600, 500)

            self.roi[0], self.roi[1] = window.topleft
            self.roi[2], self.roi[3] = window.bottomright

        elif self.os == 'Linux':
            print("Linux OS requires game window calibration")
            self.calibrate_screen()
            print("Calibration complete")
            print()
Пример #7
0
 def isWindow(title):
     """
     Verifica se existe uma janela como determinado título, 
     não fazendo diferença entre letras maiúsculas ou minúsculas.
     """
     for title_ in pygetwindow.getAllTitles():
         if title_.lower() == title.lower(): return True
Пример #8
0
    def getWindow(hWnd=None, title=None):
        """
        Método para obter uma instância de pygetwindow.Window.
        """

        # Caso tenha sido passado um hWnd, será retornado uma instância através dele.
        if isinstance(hWnd, int):
            window = pygetwindow.Window(hWnd)

        # Caso tenha sido passado um título, será retornado uma instância utilizando o título.
        elif title and isinstance(title, str):

            # Para que não haja muitos problemas, letras maiúsculas e minúsculas
            # não farão diferença para obter uma janela.
            for title_ in pygetwindow.getAllTitles():
                if title_.lower() == title.lower():
                    title = title
                    break

            window = pygetwindow.getWindowsWithTitle(title)[0]

        # Caso não tenha sido passado um título, será retornando uma instância da janela ativa.
        else:
            window = pygetwindow.getActiveWindow()

        # Retorna a janela.
        return window
Пример #9
0
async def waitForWindow():

    # new window
    global window

    while not bool(window):

        if "Overwatch" not in pw.getAllTitles():
            await asyncio.sleep(delay["interval"])
            continue

        else:
            window = pw.getWindowsWithTitle("Overwatch")[0]

    # dimensions: [[ratio x, ratio y], scale]
    dimensions = [[16, 9], 40]

    # optional config variable "window"
    # format: [16:9, 20] (ratio, scale)
    if os.getenv('window'):
        try:
            dimensions = os.getenv('window').replace('[', '').replace(
                ']', '').split(', ')
            dimensions = [[
                float(dimensions[0].split(':')[0]),
                float(dimensions[0].split(':')[1])
            ],
                          float(dimensions[1])]

        except:
            cprint(
                "\nwindow config variable must follow this format:\n[16:9, 40] (example for a 16:9 window with 40px scale)",
                "red")
            raise InvalidVariables

    # window dimensions
    scalar = dimensions[1]
    ratio = {
        "x": dimensions[0][0],
        "y": dimensions[0][1],
    }

    # pixel sizes
    x = int(ratio.get("x") * scalar)
    y = int(ratio.get("y") * scalar)

    # y height -40 for windows title
    window.resizeTo(x, y + 40)
    window.moveTo(20, 20)

    print(
        f'{ happy() }: Window minimized to { colored(x, "red") } x { colored(y, "red") } pixels'
    )

    # wait for the window to be active
    await wait(delay.get("overwatch"))

    window.activate()
Пример #10
0
def is_open(windowname):
    """
    if window is open returns true
    example : is_open("Notepad")
    """
    windows = gw.getAllTitles()
    if windows.count(windowname) > 0:
        return True
    else:
        return False
Пример #11
0
def get_multimc_window_title() -> str:
    windowTitles = gw.getAllTitles()

    for title in windowTitles:
        if 'multimc' in title.lower():
            print(title)
            return title

    pprint(windowTitles)
    raise Exception("Could not find window title containing 'MultiMC'!")
Пример #12
0
def get_application() -> List:
    titles = gw.getAllTitles()
    titles = [x for x in titles if x]

    print("Choose the presentation window from the active windows below: ")

    for id1, title in enumerate(titles):
        print("{}. {}".format(id1 + 1, title))

    window_option = int(
        input("Enter the option number ({} - {})".format(1, len(titles))))
    return titles[window_option - 1]
Пример #13
0
 def auto_send():
     global keyboard
     stuff = gw.getAllTitles()
     print(stuff)
     if 'Path of Exile' in stuff:
         abc = gw.getWindowsWithTitle('Path of Exile')[0]
         abc.activate()
         time.sleep(.01)
         message = '\n' + data
         keyboard.type(message)
     else:
         MessageBox = ctypes.windll.user32.MessageBoxW
         MessageBox(None, 'Path of Exile not running.', 'Error', 0)
def getWindowNames():
    visibleWindows = []

    #if gw.getWindowsWithTitle('Fotocamera'):
    #    visibleWindows.append('Fotocamera')

    for i in gw.getAllTitles():
        notepadWindow = gw.getWindowsWithTitle(i)[0]

        if notepadWindow.isMinimized or notepadWindow.isMaximized:
            print(notepadWindow.title)
            visibleWindows.append(notepadWindow.title)

    return visibleWindows
Пример #15
0
def get_active_dos_window():
    titles = pygetwindow.getAllTitles()
    dosbox_title = None
    for title in titles:
        if "DOSBox 0.74" in title:
            dosbox_title = title

    if dosbox_title == None:
        raise IOError from None

    print(dosbox_title)

    window = pygetwindow.getWindowsWithTitle(dosbox_title)[0]
    if window == None:
        print("No Window!")
        raise IOError from None
    return window
Пример #16
0
    def focus_window_containing(self, name):
        """ Set the found window in the foreground.

            Parameters
            ----------
            name: str
                The name or a part of the name of the searched window.
            
            Raises
            ------
            RobotException
                If not any window containing the name or part of the name given has been found.
        """

        for title in gw.getAllTitles():
            if name in title:
                self.handle = gw.getWindowsWithTitle(title)[0]
                self.handle.activate()
                break

        if self.handle is None:
            RobotException().no_window_containing_text_exception(name)
Пример #17
0
    def focus_window_with_exact_name(self, name):
        """ Set the found window in the foreground.

            Parameters
            ----------
            name: str
                The exact name of the searched window.
            
            Raises
            ------
            RobotException
                If not any window with the name given has been found.
        """

        for title in gw.getAllTitles():
            if name == title:
                self.handle = gw.getWindowsWithTitle(title)[0]
                self.handle.activate()
                break

        if self.handle is None:
            RobotException().no_window_matching_name_exception(name)
Пример #18
0
def detector():
    # initialize variable to determine if the player could be paused
    possibly_paused = False
    # stays running indefinitely, sleep functions help reduce load
    while True:
        sleep(0.5)
        if checkIfProcessRunning():
            # gets titles of all actively running programs
            titles = gw.getAllTitles()

            # looks if one of the program titles is Advertisement or Spotify, which is what Spotify is called only when it's playing an ad
            if 'Spotify Free' not in titles:
                possibly_paused = False

            # if the program title is Spotify Free, there could be an ad or Spotify could be paused
            if 'Spotify Free' in titles:
                if not possibly_paused:
                    # restarting Spotify quickly makes it repeat the last track
                    sleep(2)
                    ad('Spotify Free')
                    # only unpauses tracks that have just started, detecting if it was paused or not! P.S. Will start music on the track you left off at
                    # press('prevtrack')
                # means Spotify is either paused or playing a type of ad
                possibly_paused = True
                sleep(60)

            elif 'Advertisement' in titles or 'Spotify' in titles:
                if 'Advertisement' in titles:
                    # restarting Spotify quickly makes it repeat the last track
                    ad('Advertisement')

                if 'Spotify' in titles:
                    ad('Spotify')

                # press('playpause') can be used instead but slower
                press('nexttrack')
                sleep(60)
def browser():
    global brow, final_browser, load_time, reg_path
    flag = 0
    with OpenKey(HKEY_CURRENT_USER, reg_path) as key:
        brow = list(QueryValueEx(key,'ProgId'))
    BROWSER = ["firefox","chrome","edge","opera"]
    for i in BROWSER:
        if brow[0].lower().find(i) != -1:
            final_browser = i
    apps = pgw.getAllTitles()
    open_apps = []
    for i in apps:
        if i != "":
            open_apps.append(i.lower())
    for i in open_apps:
        if i.find(final_browser) != -1:
            flag = 0
            break
        else:
            flag = 1

    if flag == 1:
        web.open("-n")
        print ("\n\n\t\t\tTHE DEFAULT BROWSER IS NOT OPEN. OPENING DEFAULT BROWSER!!!!\n\n")
Пример #20
0
    return arrowedLine(imgPic, (2260, 1175), (2260 + changeX, 1175 - changeY),
                       width=15,
                       color=(255, 0, 0))


#-------------------------------------------------------------------------------------------
st.header("Adjust Location")
st.markdown(
    'This is an automated process that uses a control of the mouse on your screen to calculate all the data. '
    + 'Please **DON\'T** touch the mouse during the process')

openApplication = st.button("Get Sample Image")
runDone = False
if openApplication:
    # Open Applicaation
    appApplicationsStartMenu = pygetwindow.getAllTitles()
    if 'Google Earth Pro' not in appApplicationsStartMenu:
        ms.moveTo(522, 2115)
        ms.click()
        ms.typewrite("Google Earth")
        time.sleep(1)
        ms.typewrite(["enter"])
        time.sleep(3)
    else:
        #print("Already Up")
        # Open Google Earth at from task bar
        ms.moveTo(2197, 2104, duration=0.5)
        time.sleep(0.5)
        ms.click()
        # time.sleep(2)
    # Move Window
Пример #21
0
    p = p.crop((230, 80, 1900, 920))
    p.save(os.getcwd() + PICTURES_FOLDER + IMG_SUBNAME + str(now) + PNG)

    return os.getcwd() + PICTURES_FOLDER + IMG_SUBNAME + str(now) + PNG


if __name__ == "__main__":
    verbose = False
    seconds = 1
    number_of_screenshots = 3
    print("Started script: " + datetime.now().strftime("%H:%M:%S"))
    end_time = datetime.now() + timedelta(seconds=number_of_screenshots)
    print("Script will end at: " + end_time.strftime("%H:%M:%S"))

    if verbose:
        z1 = gw.getAllTitles()
        print(z1)

    this = gw.getWindowsWithTitle(WINDOW_TITLE)[0]
    this.maximize()

    for a in range(number_of_screenshots):

        path = take_screenshot(seconds)
        processed_path = detect_objects(path)

        if processed_path != 'no_objects':

            def thread_function(processed_path_image):
                email_sender = EmailThread(processed_path_image)
                email_sender.start()
Пример #22
0
from pypresence import Presence
import time
import pygetwindow as gw

client_id = '826404931153821786'
RPC = Presence(client_id)
RPC.connect()
Start = time.time()

while True:
    title = str()
    for i in gw.getAllTitles():
        if '\u200e- Adobe XD' in i:
            title = i.replace(' ‎- Adobe XD', '')
    if title == str():
        print('Adobe XD를 찾지 못했습니다.')
        time.sleep(1)
        continue
    else:
        RPC.update(details=title,
                   buttons=[{
                       "label": "Adobe XD",
                       "url": "https://www.adobe.com/kr/products/xd.html"
                   }],
                   large_image='xd',
                   start=int(Start))
        time.sleep(1)
Пример #23
0
 def mouseset(self):
     y = gw.getAllTitles()
     if 'Doodle Game!' in y:
         this = gw.getWindowsWithTitle(r'Doodle Game!')[0].topleft
         pyautogui.moveTo(this.x, this.y)
         return this.x, this.y
Пример #24
0
 def set_display_name(self):
     display_list = pygetwindow.getAllTitles()
     shmoo_tool_list = [s for s in display_list if "テキストエディット" in s]
     self.display_name = shmoo_tool_list[0]
Пример #25
0
def hasWhatsAppOpen():
    apps = gw.getAllTitles()
    for i in range(len(apps)):
        if str(apps[i]) == appName or len(str(apps[i])) == len(appName):
            return len(gw.getWindowsWithTitle(appName)) > 0
Пример #26
0
from MahjongSoulImage.itemControl import *
from Julius import *


itemControl = ItemControl()

# template = cv2.imread("template1.png", 0)

# イメージインスタンス
# img = ImageGrab.grab()

# データをバッファに格納
# buffer = io.BytesIO()
# img.save(buffer, "BMP")

titles = gw.getAllTitles()
handle = None

for item in titles:
    if("雀魂" in item):
        handle = ctypes.windll.user32.FindWindowW(0, item)
        break

# 雀魂が見つかったとき
if(handle != None):
    game = MahjongSoul(handle)
    julius = Julius()
    hai_list = list()

    for i in range(10000000):
        try:
Пример #27
0
import pygetwindow as gw
import cv2 as cv2

import time

# code goes here
print(gw.getAllTitles())
KEY_A = 0x41

KEYEVENTF_EXTENDEDKEY = 0x0001
KEYEVENTF_KEYUP = 0x0002
#######################################################################################################################

pyautogui.FAILSAFE = True  #Moving mouse to top left of screen will abort execution
pyautogui.PAUSE = 1  #Seconds to wait between each pyautogui API call

screenWidth, screenHeight = pyautogui.size()
pyautogui.moveTo(screenWidth / 2,
                 screenHeight / 2)  #Move to middle of screen each loop

#Ensure Black Desert Window is active window
r = re.compile("BLACK DESERT.*")
windowList = gw.getAllTitles()
bdo = list(filter(r.match, windowList))[0]
gw.getWindowsWithTitle(bdo)[0].activate()
time.sleep(1)
# keyboard = Controller()
# keyboard.press(Key.enter)
# time.sleep(0.2)
# keyboard.release(Key.enter)

i.SendInput(i.Keyboard(VK_RETURN))
time.sleep(0.2)
i.SendInput(i.Keyboard(VK_RETURN, KEYEVENTF_KEYUP))
time.sleep(0.2)
i.SendInput(i.Keyboard(KEY_H))
time.sleep(0.2)
i.SendInput(i.Keyboard(KEY_H, KEYEVENTF_KEYUP))
Пример #29
0
    "verdefoglia": "firered-leafgreen"
}

winPath = "pokemon\\gen3\\" + games[selected] + ("\\back" if starter else
                                                 "") + "\\shiny\\"
macPath = "pokemon/gen3/" + games[selected] + ("/back"
                                               if starter else "") + "/shiny/"
shinyPath = winPath if sys.platform == "win32" else macPath

update(selected, games, shinyPath)

shiny = eval(open(games[selected] + "Shiny.txt", "r").read())

vbawindow = None

for window in gw.getAllTitles():
    if "VisualBoyAdvance" in window:
        vbawindow = gw.getWindowsWithTitle(window)[0]

#mette focus sulla finestra e la sposta a (0,0)
vbawindow.activate()
vbawindow.moveTo(0, 0)

#salva prima
ag.hotkey("shift", "f" + data["saveslot"])
time.sleep(1)

trovato = False
counter = 0
while not trovato:
    counter += 1
Пример #30
0
def detect_window(name):
    if name in pw.getAllTitles():
        emulator = pw.getWindowsWithTitle(name)[0]
        emulator.maximize()