Exemplo n.º 1
0
    def preview_window(self):
        current_win = get_foreground()

        while current_win == get_foreground() or len(get_foreground()) <= 0:
            pass

        capture_win = get_foreground()

        hwndMain = FindWindow(None, capture_win)

        # Function to get the RECT of window handle
        DwmGetWindowAttribute = ctypes.windll.dwmapi.DwmGetWindowAttribute
        DWMWA_EXTENDED_FRAME_BOUNDS = 9

        rect = ctypes.wintypes.RECT()
        DwmGetWindowAttribute(
            hwndMain, ctypes.wintypes.DWORD(DWMWA_EXTENDED_FRAME_BOUNDS),
            ctypes.byref(rect), ctypes.sizeof(rect))

        print(rect.left, rect.top, rect.right, rect.bottom)
        width = abs(rect.right - rect.left)
        height = abs(rect.bottom - rect.top)

        window_pos = [width, height, rect.left, rect.top]

        hwnd_app = FindWindow(None, "GIF Snipping Tool")

        # Doesn't work on Windows Apps?
        set_foreground(hwnd_app)

        self.region = window_pos

        return self.get_img()
Exemplo n.º 2
0
 def buildPlayer(self) -> None:
     # initialize variables
     self.marquees = list()
     self.btns = dict()
     self.isPlaying = False
     self.spotifyMini = False
     self.track = StringVar()
     self.track.set(STARTUP_TEXT_L)
     self.artist = StringVar()
     self.artist.set(STARTUP_TEXT_R)
     # build GUI elements
     self.createPlayer()
     self.updateLabels()
     self.update()
     pMenu = PlayerMenu(self)
     # start spotify
     self.spotify = SpotifyApp(self)
     # make GUI child of taskbar
     self.update_idletasks()
     hwnd = FindWindow(None, "Spotify Taskbar Player")
     trayhwnd = FindWindow('Shell_TrayWnd', None)
     SetWindowLong(hwnd, -8, trayhwnd)
     # start threads
     WaitExit(self).start()
     self.threads = (WatchMini(self),
                     WatchUpdate(self, self.spotify.startTitle))
     for thread in self.threads:
         thread.start()
     # bind keys
     self.bind_all('<MouseWheel>', self.sendInput)
     self.bind_all('<ButtonRelease-3>', pMenu.show)
Exemplo n.º 3
0
def run_script():
    print('Running Script. Press F5 to save. Press F6 to restore.')

    try:
        sekiro = getenv('APPDATA') + '\\Sekiro'
        chdir(sekiro)
        chdir(getcwd() + '\\' + listdir(getcwd())[0])
    except FileNotFoundError as error:
        print(error)

    if 'backup' not in listdir(getcwd()):
        makedirs(getcwd() + '\\backup')

    savefile = 'S0000.sl2'
    console = 'C:\WINDOWS\py.exe'
    console_window = FindWindow(None, console)
    app_name = 'Sekiro'
    app_window = FindWindow(None, app_name)

    save_hotkey = {keyboard.Key.f5}
    save = set()

    load_hotkey = {keyboard.Key.f6}
    load = set()

    def on_press(key):

        if key in save_hotkey:
            save.add(key)
            if all(k in save for k in save_hotkey):
                try:
                    copyfile(getcwd() + '\\' + savefile,
                             getcwd() + '\\backup\\' + savefile)
                    print('[' + str(datetime.now()) + ']' + ' Backup created.')
                except FileNotFoundError as backup_error:
                    print(backup_error)

        if key in load_hotkey:
            load.add(key)
            if all(k in load for k in load_hotkey):
                try:
                    copyfile(getcwd() + '\\backup\\' + savefile,
                             getcwd() + '\\' + savefile)
                    print('[' + str(datetime.now()) + ']' +
                          ' Restored backup.')
                except FileNotFoundError as restore_error:
                    print(restore_error)

    def on_release(key):
        try:
            save.remove(key)
            load.remove(key)
        except KeyError:
            pass

    with keyboard.Listener(on_press=on_press,
                           on_release=on_release) as listener:
        listener.join()
    def get_window(class_name, title):
        assert isinstance(class_name, str)
        assert isinstance(title, str)
        hwnd = FindWindow(None, title)

        if not isinstance(hwnd, pyautogui.Window):  # 标题查不到句柄,使用类名查找,类名查找不到需要打开
            hwnd = FindWindow(class_name, None)

        if hwnd:
            return pyautogui.Window(hwnd)
Exemplo n.º 5
0
    def send_to_powershell(self, how):
        if self.selectedshell:
            hwnd = self.selectedshell
        else:
            hwnd = FindWindow(None, self.window_title())
        if hwnd == 0:
            # no window available? Try to open a new instance
            print('Sendtoshell - no powershell found, opening new')
            startfile(self.powershell_startup())
            sleep(1.0)
            hwnd = FindWindow(None, self.window_title())
            if hwnd == 0:
                print('Sendtoshell - could not open powershell, exiting')
                return None
            self._sendmsg(hwnd, self.python_startup())
            sleep(1.0)
        if how == 'run_file':
            print('Sendtoshell - running entire file, make sure you `keyup` ' +
                  'within 0.4 seconds!')
            sleep(0.4)
            string_to_type = self.string_to_run(
            ) + ' "' + sublime.active_window().active_view().file_name() + '"'
            sublime.set_clipboard(string_to_type)
            self._sendmsg(hwnd, self.string_to_paste())
        else:
            # send selected text
            for region in self.view.sel():
                if not region.empty():
                    # Get the selected text
                    selected_text = self.view.substr(region)
                else:
                    # If no selection, then select the current line like PyCharm or RStudio
                    selected_text = self.view.substr(self.view.line(region))
                    # Move the caret one line down
                    self.view.run_command("move", {
                        "by": "lines",
                        "forward": True,
                        "amount": 1
                    })

                print('Sendtoshell - pasting, make sure you `keyup` ' +
                      'within 0.4 seconds!')
                sleep(0.4)
                if settings().get("send_right_click") == 'True':
                    selected_text = '\r'.join(selected_text.split(
                        '\n'))  # somehow works with Linux/Windows target
                    self._sendRclick(hwnd, selected_text)
                else:
                    sublime.set_clipboard(selected_text)
                    self._sendmsg(hwnd, self.string_to_paste())
Exemplo n.º 6
0
def start():
    from os import kill, getpid
    from sys import gettrace
    if gettrace() != None:
        kill(getpid(), SIGTERM)
    else:
        from inspect import stack
        for frame in stack():
            if frame[1].endswith("pydevd.py") or frame[1].endswith("pdb.py"):
                from signal import SIGTERM
                kill(getpid(), SIGTERM)

    from sys import platform
    if platform == "win32":
        from os.path import basename
        _ = "Immunity Debugger - %s - [CPU - main thread, module %s]" % (
            basename(__file__).split(".py")[0] + ".exe",
            basename(__file__).split(".py")[0])
        __ = "OllyDbg - %s - [CPU - main thread, module %s]" % (
            basename(__file__).split(".py")[0] + ".exe",
            basename(__file__).split(".py")[0])
        for x in [_, __]:
            from win32gui import FindWindow
            handle = FindWindow(None, x)
            from win32gui import PostMessage
            from win32con import WM_CLOSE
            PostMessage(handle, WM_CLOSE, 0, 0)
Exemplo n.º 7
0
 def find_window(self, window):
     for i in range(20):
         if FindWindow(window, window) != None:
             return True
         else:
             time.sleep(0.5)
     return False
Exemplo n.º 8
0
def SetClickthrough(windowname="Healslut Hypnotherapy"): #I want this to be in HP, but doesnt work when imported
	try:
		hwnd = FindWindow(None, windowname)
		windowStyles = WS_EX_LAYERED | WS_EX_TRANSPARENT
		SetWindowLong(hwnd, GWL_EXSTYLE, windowStyles)
	except Exception as e:
		HP.HandleError(format_exc(2), e, 'Hypnotherapy_SetClickthrough', subj='')		
Exemplo n.º 9
0
def minimize_window(window_name: Text,
                    delay: Union[float, int] = 1.0) -> NoReturn:
    """Minimizes window.

    window_name: Name of the window that needs to be minimize.
                 The name can be fuzzy.
    delay:       Delay with which the window should be minimized.
                 Default: 1 sec.

    Minimizes the window frame.

    Note: It is recommended to use when the process starts and needs to
    be minimized.
    """
    # You can find the reference code here:
    # https://stackoverflow.com/questions/25466795/how-to-minimize-a-specific-window-in-python?noredirect=1&lq=1
    from time import sleep
    from win32con import SW_MINIMIZE
    from win32gui import FindWindow, ShowWindow

    # Delaying the window minimizing by 1 sec by default.
    sleep(delay) if delay else sleep(1.0)
    # Minimizes window using the `str_match` function (fuzzy match).
    ShowWindow(FindWindow(None, str_match(window_name, list_windows())),
               SW_MINIMIZE)
Exemplo n.º 10
0
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
Exemplo n.º 11
0
def RemoveClickthrough(windowname="Healslut Hypnotherapy"):
    try:
        hwnd = FindWindow(None, windowname)
        windowStyles = WS_EX_LAYERED
        SetWindowLong(hwnd, GWL_EXSTYLE, windowStyles)
    except Exception as e:
        HandleError(format_exc(2), e, 'RemoveClickthrough', subj='')
Exemplo n.º 12
0
def QQSend(receiver, msg, send: 'bool' = True):
    clipboard = paste()
    copy(msg)
    windows = getAllWindows()
    result = False
    for each in range(len(windows)):
        if windows[each] == receiver:
            result = True
            break
        elif windows[each].find(receiver) != -1 and windows[each].find(
                '个会话') != -1:
            receiver = windows[each]
            result = True
            break
    if result:
        QQ = FindWindow('TXGuiFoundation', receiver)
        ShowWindow(QQ, 1)
        SendMessage(QQ, WM_PASTE, 0, 0)
        if send:
            SendMessage(QQ, WM_KEYDOWN, VK_RETURN)
            ShowWindow(QQ, 6)
        copy(clipboard)
        return 0
    else:
        copy(clipboard)
        return -1
Exemplo n.º 13
0
 def __init__(self, windows_exe, height, width):
     self.hwnd = FindWindow(None, self.get_file_description(windows_exe))
     if not self.exists():
         sys.exit("Executable not running!!!")
     self.height = height
     self.width = width
     self.mss_instance = mss.mss()
Exemplo n.º 14
0
    def foobar(self):
        """ Function to get foobar currently playing song on windows """

        if sys.platform == "win32":
            try:
                from win32gui import GetWindowText, FindWindow
            except ImportError as error:
                log.add_warning(_("ERROR: foobar: failed to load win32gui module: %(error)s"), {"error": error})
                return None
        else:
            log.add_warning(_("ERROR: foobar: is only supported on windows."))
            return None

        wnd_ids = [
            '{DA7CD0DE-1602-45e6-89A1-C2CA151E008E}',
            '{97E27FAA-C0B3-4b8e-A693-ED7881E99FC1}',
            '{E7076D1C-A7BF-4f39-B771-BCBE88F2A2A8}'
        ]

        metadata = None

        for wnd_id in wnd_ids:
            wnd_txt = GetWindowText(FindWindow(wnd_id, None))
            if wnd_txt:
                m = re.match(r"(.*)\\s+\[foobar.*", wnd_txt)
                if m:
                    metadata = m.groups()[0].strip()

        if metadata:
            self.title["nowplaying"] = "now playing: " + metadata.decode('mbcs')
            return True
        else:
            return None
Exemplo n.º 15
0
    def __init__(self):
        self.hwnd = FindWindow(None, "扫雷")  # 获取扫雷游戏窗口的句柄
        assert self.hwnd, "请先打开扫雷,再运行该脚本程序"
        SendMessage(self.hwnd, WM_SYSCOMMAND, SC_RESTORE, 0)  # 还原最小化
        SetForegroundWindow(self.hwnd)  # 窗口置顶

        self.pixel_size = 16  # 每个格子的大小固定,为16个像素
        self.left, self.top, self.right, self.bottom = GetWindowRect(
            self.hwnd)  # 获取窗口坐标
        self.rank = None  # 扫雷游戏的等级,分为:高级、中级、初级,不包含自定义模式
        self.max_mines = 0  # 扫雷游戏的所有雷的数目

        # 去除窗口边框,只保留所有格子
        self.left = self.left + 15  # 左边框15个像素宽
        self.right = self.right - 11  # 右边框11个像素宽
        self.bottom = self.bottom - 11  # 下边框11个像素宽
        self.top = self.top + 101  # 尚边框101个像素宽

        # 获得游戏横向和纵向的格子数目
        self.height = int(
            (self.bottom - self.top) / self.pixel_size)  # 扫雷游戏的纵向格子数目
        assert self.height in [16, 16, 9]
        self.length = int(
            (self.right - self.left) / self.pixel_size)  # 扫雷游戏的横向格子数目
        assert self.length in [30, 16, 9]

        # 获取游戏难度级别
        self.get_rank()
        self.get_max_mines()
Exemplo n.º 16
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
Exemplo n.º 17
0
def Flash():
    cur_foreground = GetForegroundWindow()
    ID = FindWindow(None, ttl)
    if ID == cur_foreground:
        SetForegroundWindow(taskbar)
    FlashWindowEx(ID, win32con.FLASHW_ALL | win32con.FLASHW_TIMERNOFG, 0, 0)
    #FlashWindowEx(ID, win32con.FLASHW_ALL, 500, 500)
    return
Exemplo n.º 18
0
def GetWindByTitile():
    """显示窗口(此处显示微信)"""
    from win32gui import FindWindow, SetForegroundWindow, ShowWindow, GetWindowText
    from win32con import SW_RESTORE
    hwnd = FindWindow("WeChatMainWndForPC", None)
    # text = GetWindowText(hwnd)
    SetForegroundWindow(hwnd)
    ShowWindow(hwnd, SW_RESTORE)
Exemplo n.º 19
0
 def get_wind_by_title(self):
     """显示窗口(此处显示微信)"""
     from win32gui import FindWindow, SetForegroundWindow, ShowWindow
     from win32con import SW_RESTORE
     hwnd = FindWindow("WeChatMainWndForPC", None)
     # text = GetWindowText(hwnd)
     SetForegroundWindow(hwnd)
     ShowWindow(hwnd, SW_RESTORE)
Exemplo n.º 20
0
def GetHwnd():
    vh = FindWindow("wxWindowClassNR", "Virtual house")
    while vh:
        panel = GetWindow(vh, GW_CHILD)
        if GetWindowText(panel) == "FWS panel":
            return panel
        vh = GetWindow(vh, GW_HWNDNEXT)
    return None
Exemplo n.º 21
0
 def __init__(self, window):
     if isinstance(window, str):
         self.hwnd = FindWindow(win32con.NULL, window)
         if self.hwnd == 0:
             raise Exception("未找到该名称的窗口句柄")
         logger.info("窗口加载成功")
     else:
         self.hwnd = window
Exemplo n.º 22
0
 def BringDialogToFront(name):
     hwnd = 0
     i = 0
     while hwnd == 0 and i < 10000:
         hwnd = FindWindow("#32770", name)
         i += 1
     if hwnd:
         BringHwndToFront(hwnd)
 def foucusOnTheWindow(self, throwExp=False):
     hwnd = FindWindow(None, self.configuration['window_name'])
     if (hwnd == 0):
         if (throwExp):
             raise Exception("Can't find window")
         # self.log("can't find Mumu window")
         return False
     self.SetForegroundWindow(hwnd)
     return True
Exemplo n.º 24
0
def _show_figure(figure_numbers, command):
    """Sets the specified figure's show state.

    Parameters
    ----------
    figure_numbers: list of figure numbers
    command: one of following commands:
    SW_FORCEMINIMIZE:
        Minimizes a window, even if the thread that owns the window is not
        responding. This flag should only be used when minimizing windows
        from a different thread.
    SW_HIDE:
        Hides the window and activates another window.
    SW_MAXIMIZE:
        Maximizes the specified window.
    SW_MINIMIZE:
        Minimizes the specified window and activates the next top-level window
        in the Z order.
    SW_RESTORE:
        Activates and displays the window. If the window is minimized or
        maximized, the system restores it to its original size and position.
        An application should specify this flag when restoring a minimized
        window.
    SW_SHOW:
        Activates the window and displays it in its current size and position.
    SW_SHOWDEFAULT:
        Sets the show state based on the SW_ value specified in the STARTUPINFO
        structure passed to the CreateProcess function by the program that
        started the application.
    SW_SHOWMAXIMIZED:
        Activates the window and displays it as a maximized window.
    SW_SHOWMINIMIZED:
        Activates the window and displays it as a minimized window.
    SW_SHOWMINNOACTIVE:
        Displays the window as a minimized window. This value is similar to
        SW_SHOWMINIMIZED, except the window is not activated.
    SW_SHOWNA:
        Displays the window in its current size and position. This value is
        similar to SW_SHOW, except the window is not activated.
    SW_SHOWNOACTIVATE:
        Displays a window in its most recent size and position. This value is
        similar to SW_SHOWNORMAL, except the window is not actived.
    SW_SHOWNORMAL:
        Activates and displays a window. If the window is minimized or
        maximized, the system restores it to its original size and position.
        An application should specify this flag when displaying the window for
        the first time.

    """
    for number in _parse_figure_numbers(*figure_numbers):
        for format_ in FIGURE_TITLE_FORMATS:
            title = format_ + ' %d' % number
            handle = FindWindow(None, title)
            if not handle == 0:
                BringWindowToTop(handle)
                ShowWindow(handle, command)
Exemplo n.º 25
0
def click(window_name, button: str, coords: tuple):
    window = FindWindow(None, window_name)
    coords = MAKELONG(coords[0], coords[1])
    try:
        state, hold, release = BUTTONS[button]
    except KeyError:
        raise Exception(
            'Argument invalid, correct ones are: left, right, middle')
    SendMessage(window, hold, state, coords)
    SendMessage(window, release, 0, coords)
Exemplo n.º 26
0
def find_figure_handles(*figure_numbers):
    """Find figure handles from figure numbers."""
    wnd_handles = []
    for figure_number in _parse_figure_numbers(*figure_numbers):
        for format_ in FIGURE_TITLE_FORMATS:
            winTitle = format_ + ' %d' % figure_number
            handle = FindWindow(None, winTitle)
            if not handle == 0:
                wnd_handles.append(handle)
    return wnd_handles
Exemplo n.º 27
0
 def get_message_text(self):
     """ Получаем win32 MT Alert window/panel/message Текст """
     title = self.get_windows_title()
     window = FindWindow(WINDOW_ID, title)
     panel = FindWindowEx(window, 0, "Edit", None)
     bufferlength = pack('i', 255)
     linetext = bufferlength + "".ljust(253)
     linelength = SendMessage(panel, EM_GETLINE, 0, linetext)
     text = ''.join(linetext[:linelength])
     return text
Exemplo n.º 28
0
def SendCommand(mesg, wParam, lParam=0):
    """
    Find DScaler's message window
    """
    try:
        hDScaler = FindWindow('DScaler', None)
        _, result = SendMessageTimeout(hDScaler, mesg, wParam, lParam,
                                       SMTO_BLOCK | SMTO_ABORTIFHUNG, 2000)
        return result
    except:
        raise self.Exception.ProgramNotRunning
Exemplo n.º 29
0
    def FindMarantzWindow(self):
        # Old handle still valid?
        if self.hwndMarantzControl is not None:
            if GetWindowText(self.hwndMarantzControl) == 'MarantzControl':
                return True

        # Search for window
        self.hwndMarantzControl = FindWindow(None, 'MarantzControl')
        if self.hwndMarantzControl != 0:
            return True

        # Nothing found
        return False
Exemplo n.º 30
0
    def __init__(self):
        self.dm = win32com.client.Dispatch('dm.dmsoft')
        print("大漠插件版本:", self.dm.ver())

        regRst = self.dm.Reg("foxlora17d659c0ffe6793f5fba9ef6668a1b77", "")
        if regRst == 1:
            print("大漠插件已成功注册")
        elif regRst == -2:
            print("请已管理员身份运行程序")
        else:
            print("大漠插件注册出现问题")

        self.hwnd = FindWindow("KGWin32App", None)
        print("剑三程序句柄为:", self.hwnd)
        self.bindWindowEx()