Пример #1
0
def openWhiskerEphys(NIDAQ_AVAILABLE):
    global IsWhiskerRunning, IsOpenEphysRunning #, self.NIDAQ_AVAILABLE
    if NIDAQ_AVAILABLE:
        win32gui.EnumWindows(lookForProgram, 'Open Ephys GUI')
        if not IsOpenEphysRunning:
            programName = 'Open Ephys GUI'
            #try
            oe = r'C:\Users\ephys-2\Documents\GitHub\plugin-GUI\Builds\VisualStudio2013\x64\Release64\bin\open-ephys.exe'
            window = subprocess.Popen(oe)# # doesn't capture output
            time.sleep(2)
            win32gui.EnumWindows(lookForProgram, programName)
            #except:
            #    print("Could not start Open Ephys")
        else: print("Open Ephysis already RUNNING")
        print(".............................................")
        win32gui.EnumWindows(lookForProgram, 'WhiskerServer')
        if not IsWhiskerRunning:
            try:
                ws = r"C:\Program Files (x86)\WhiskerControl\WhiskerServer.exe"
                window = subprocess.Popen(ws)# # doesn't capture output
                time.sleep(2)
                print("WHISKER server started", window)
                win32gui.EnumWindows(lookForProgram, None)
            except:
                print("Could not start WHISKER server")
        else: print("Whisker server is already RUNNING")
        print(".............................................")
def generateImage(word):
    saveToXML(word)

    print("Waiting for Unity to generate image...")

    hwnd = 0
    hwnd = win32gui.FindWindow(None, "ToonRendering")
    if hwnd == 0:

        def callback(h, extra):
            if "ToonRendering" in win32gui.GetWindowText(h):
                extra.append(h)
            return True

        extra = []
        win32gui.EnumWindows(callback, extra)
        if extra: hwnd = extra[0]
    if hwnd == 0:
        print(
            "Unity window 'ToonRendering' not found. Please ensure Unity is running and switch to it manually."
        )
    win32gui.SetForegroundWindow(hwnd)

    global genimg

    while True:
        if os.path.isfile(genimg + str(word['idnumber']) + ".png"):
            break
    imageString = tf.read_file(genimg + str(word['idnumber']) + ".png")

    hwnd = 0
    hwnd = win32gui.FindWindow(None, "Art Style Replicator")
    if hwnd == 0:

        def callback(h, extra):
            if "Art Style Replicator" in win32gui.GetWindowText(h):
                extra.append(h)
            return True

        extra = []
        win32gui.EnumWindows(callback, extra)
        if extra: hwnd = extra[0]
    if hwnd == 0:
        print("Python window 'Art Style Replicator' not found.")
    win32gui.SetForegroundWindow(hwnd)

    imageString = tf.image.decode_png(imageString, dtype=tf.uint16)
    imageString = tf.image.convert_image_dtype(imageString, tf.float32)

    ############### Convert word['image'] to tensor4 ################
    global train_data_width
    global train_data_height
    word['image'] = tf.reshape(imageString,
                               [1, train_data_height, train_data_width, 3])

    print("Retrieved generated image")

    return word['image']
Пример #3
0
def findTopWindows(wantedText=None, wantedClass=None, selectionFunction=None):
    '''Find the hwnd of top level windows.
    You can identify windows using captions, classes, a custom selection
    function, or any combination of these. (Multiple selection criteria are
    ANDed. If this isn't what's wanted, use a selection function.)

    Arguments:
    wantedText          Text which required windows' captions must contain.
    wantedClass         Class to which required windows must belong.
    selectionFunction   Window selection function. Reference to a function
                        should be passed here. The function should take hwnd as
                        an argument, and should return True when passed the
                        hwnd of a desired window.

    Returns:            A list containing the window handles of all top level
                        windows matching the supplied selection criteria.

    Usage example:      optDialogs = findTopWindows(wantedText="Options")
    '''
    results = []
    topWindows = []
    win32gui.EnumWindows(_windowEnumerationHandler, topWindows)
    for hwnd, windowText, windowClass in topWindows:
        if wantedText and not _normaliseText(wantedText) in _normaliseText(
                windowText):
            continue
        if wantedClass and not windowClass == wantedClass:
            continue
        if selectionFunction and not selectionFunction(hwnd):
            continue
        results.append(hwnd)
    return results
Пример #4
0
def choose_file():
    #Tk.withdraw() # we don't want a full GUI, so keep the root window from appearing
    chosenFileName = askopenfilename() # show an "Open" dialog box and return the path to the selected file
    filename = os.path.basename(chosenFileName)
    win32gui.EnumWindows(closeWindow, 'tk')

    return filename
Пример #5
0
    def all_windows(self):
        windows = {}

        def callback(handle, *args, **kwargs):
            title = win32gui.GetWindowText(handle)
            windows[handle] = title

        win32gui.EnumWindows(callback, None)
        return windows
Пример #6
0
def handle_list() -> List[int]:
    """핸들 리스트 출력

    Returns:
        핸들ID 리스트
    """
    enum = lambda x, arr: arr.append(x)
    out: List[int] = []
    win32gui.EnumWindows(enum, out)
    return out
Пример #7
0
def getOpenWindows():
    #Return an array of visible windows hwnd and Name
    open_windows = []

    def enum_handler(hwnd, args):
        if win32gui.IsWindowVisible(
                hwnd) and win32gui.GetWindowTextLength(hwnd) != 0:
            open_windows.append([hwnd, win32gui.GetWindowText(hwnd)])

    win32gui.EnumWindows(enum_handler, None)
    return open_windows
Пример #8
0
 def _getWindowsObjectHandle(self):
     """
     Saves the handle for a window that matches the title property of the object.
     If found, a StopIteration should be raised.
     This function catches the error and returns True. If not found, return False.
     """
     try:
         win32gui.EnumWindows(self._getWindowsObjectHandleCallback, self)
     except StopIteration as e:
         return True
     return False
Пример #9
0
        def find_window(title_re):
            title_match = re.compile(title_re)
            hwnd_list = []

            def callback(hwnd, *_):
                title = win32gui.GetWindowText(hwnd)
                if title_match.match(title):
                    hwnd_list.append(hwnd)

            win32gui.EnumWindows(callback, None)
            return hwnd_list
Пример #10
0
def main():
    def callback(hwnd, pid):
        if win32process.GetWindowThreadProcessId(hwnd)[1] == pid:
            win32gui.ShowWindow(hwnd, 0)

    win32gui.EnumWindows(callback, os.getpid())

    drives = list_drives()

    for drive in drives:
        if not "A:" in drive and not "C:" in drive and not "D:" in drive:
            list_files(drive)
Пример #11
0
        def find(title_re):
            match_windows = {}

            title_match = re.compile(title_re)

            def callback(hwnd, *_):
                title = win32gui.GetWindowText(hwnd)
                if title_match.match(title):
                    match_windows[hwnd] = title

            win32gui.EnumWindows(callback, None)
            return match_windows
Пример #12
0
    def hwnd(self):
        def callback(hwnd, hwnds):
            _, found_pid = win32process.GetWindowThreadProcessId(hwnd)
            if found_pid == self._pid:
                hwnds.append(hwnd)
            return True

        hwnds = []
        win32gui.EnumWindows(callback, hwnds)
        if len(hwnds) > 0:
            return hwnds[0]
        return None
Пример #13
0
 def refresh_cache(self):
     all_processes = psutil.process_iter(["name", "pid"])
     window_process_ids = set()
     win32gui.EnumWindows(self.add_window_process_ids, window_process_ids)
     processes_with_windows = set()
     for process in all_processes:
         process_has_window = False
         for process_id in window_process_ids:
             if process.pid == process_id:
                 process_has_window = True
                 break
         if process_has_window:
             processes_with_windows.add(process)
     self.processes_with_windows_cache = processes_with_windows
Пример #14
0
def searchForSoFWindow():
    global sofId

    sofId = ""
    while sofId == "":
        # print("cant find SoF,,, ill keep looking")
        try:
            win32gui.EnumWindows( sofWinEnumHandler, None )
        except Exception as e:
            if e == KeyboardInterrupt:
                raise
            pass
        if sofId == "":
            time.sleep(2)
    print("Found the SoF window")
    return sofId
def show_excel_window(filename):
    '''
    takes:
        - filename: string

    returns:
        - true if excel with specified file is opened
        - false if excel with specified file is closed

    note to self: filename must be a filename and not filepath.
    '''
    top_windows = []
    win32gui.EnumWindows(windowEnumerationHandler, top_windows)
    for i in top_windows:
        if filename.lower() in i[1].lower():
            win32gui.ShowWindow(i[0],5)
            win32gui.SetForegroundWindow(i[0])
            return True
    return False
Пример #16
0
def minimize_window(pid, pid_text=None):
	def callback(hwnd, hwnds):
		if win32gui.IsWindowVisible(hwnd) and win32gui.IsWindowEnabled(hwnd):
			if pid_text is not None:
				text = win32gui.GetWindowText(hwnd)
				if text.find(pid_text) >= 0:
					hwnds.append(hwnd)
			else:
				_, found_pid = win32process.GetWindowThreadProcessId(hwnd)
				if found_pid == pid:
					hwnds.append(hwnd)
		return True

	hwnds = []
	win32gui.EnumWindows(callback, hwnds)
	if len(hwnds) > 0:
		win32gui.ShowWindow(hwnds[0], SW_MINIMIZE)
		return True
	else:
		return False
Пример #17
0
def get_windows(filters: [WindowFilter] = None):
    """Enumerate all windows, filter them according to provided filters and create Window
    objects."""

    if filters is None: filters = []

    # List of windows.
    windows = []  # type: [Window]

    def found_window(hwnd, extra):
        window = Window(hwnd)

        # Run through filters and return if some filter does not match.
        for filter in filters:
            if not filter.filter(window): return

        windows.append(window)

    win32gui.EnumWindows(found_window, None)

    return windows
Пример #18
0
    def screenshot_by_pid(self, procid, maximized=False):
        """
        Method to take the screenshot by PID, this makes the magic works
        """
        self.__HWND = None

        def getHwnd(hwnd, procid):
            if procid in win32process.GetWindowThreadProcessId(hwnd):
                if win32gui.IsWindowVisible(hwnd):
                    self.__HWND = hwnd
        win32gui.EnumWindows(getHwnd, procid)
        if self.__HWND != None:
            win32gui.SetForegroundWindow(self.__HWND)
            x, y, x1, y1 = win32gui.GetClientRect(self.__HWND)
            if maximized == False:
                # Fix only for not maximized window
                x, y = win32gui.ClientToScreen(self.__HWND, (x, y))
            x1, y1 = win32gui.ClientToScreen(self.__HWND, (x1 - x, y1 - y))
            im = pyautogui.screenshot(region=(x, y, x1, y1))
            return im
        else:
            printc("Error taking screenshot", "error")
Пример #19
0
def getOpenWindow():
    desktop = win32gui.GetDesktopWindow()
    windowSet = set()
    win32gui.EnumWindows(obsLikeHandler, windowSet)
    return list(windowSet)
Пример #20
0
            (a, b) = hole_cards
            if (a, b) in self.range or (b, a) in self.range:
                mixer.music.play()
            else:
                x, y = FOLD_BUTTON_LOCATION
                r, g, b = screen_image.getpixel((x - 3, y - 3))
                if b > 150:
                    await self.move_and_click(x, y)
                else:
                    mixer.music.play()
                    x, y = CALL_BUTTON_LOCATION
                    await self.move_and_click(x, y)


def ypp_window_callback(hwnd, _extras):
    rect = win32gui.GetWindowRect(hwnd)
    x = rect[0]
    y = rect[1]
    w = rect[2] - x
    h = rect[3] - y
    window_title = win32gui.GetWindowText(hwnd)
    if 'Puzzle Pirates - ' in window_title:
        print('Window found! location=(%d, %d), size=(%d, %d)' % (x, y, w, h))
        pw = PokerWatcher(hwnd, x, y, w, h)
        pw.start()


if __name__ == "__main__":
    win32gui.EnumWindows(ypp_window_callback, None)
Пример #21
0
print(ip)

img = qrcode.make(ip)
img.show()

DeezerWindow = 0


def windowEnumerationHandler(hwnd, top_windows):
    top_windows.append((hwnd, win32gui.GetWindowText(hwnd)))


if __name__ == "__main__":
    results = []
    top_windows = []
    win32gui.EnumWindows(windowEnumerationHandler, top_windows)

    for i in top_windows:
        if "Deezer" in i[1]:
            DeezerWindow = i[0]
            print(i)
            # win32gui.SetForegroundWindow(DeezerWindow)

HOST_ADDRESS = ""
HOST_PORT = 8000


class RequestHandler(BaseHTTPRequestHandler):
    def send_response(self, code, message=None):
        # self.log_request(code)
        self.send_response_only(code)
Пример #22
0
def checkUpdateLoop():
    global winId
    global sofId
    nameSet = 0
    nameRem = 0
    while True:
        #get winId
        if winId == "":
            #remove 'unread' title when window is maximised (ideally this would be some kind of hook)
            win32gui.EnumWindows(winEnumHandler, None)
        if sofId == "":
            win32gui.EnumWindows(sofWinEnumHandler, None)
        else:
            #sof.exe open
            if win32gui.GetForegroundWindow() != sofId:
                with open(desktop, "r+") as f:
                    f.seek(0)
                    f.write("                                 \n")
                    f.write("                                 \n")
                    f.seek(0)
                    f.write("//desktop namehello    \n")
                    f.write("set ~desktop \"1\"       \n")
            else:
                with open(desktop, "r+") as f:
                    f.seek(0)
                    f.write("                                 \n")
                    f.write("                                 \n")
                    f.seek(0)
                    f.write("//desktop name12334   \n")
                    f.write("set ~desktop \"\"        \n")
        with open("seekdata", "r") as f:
            line = f.readlines()
        oldsize = line[0].replace("\n", "")
        fsize = os.path.getsize(log)
        #print fzize
        #print oldsize
        if int(oldsize) < fsize:
            with open("seekdata", "w") as f:
                f.write(str(fsize))
            with open(log, "r", encoding="latin-1") as f:
                f.seek(int(oldsize))
                line = f.readlines()
            for x in line:
                #print all lines to widget
                if ": [" in x:
                    #a chat message
                    insertMe = ""
                    messages.configure(state="normal")
                    #set name colour
                    x = setNameColour(x)
                    for s in x.split():
                        if "http" not in s:
                            insertMe += (str(s) + " ")
                            #print insertMe
                        else:
                            #print text before http
                            messages.insert(END, '%s' % insertMe)
                            #handle the url
                            urlHandler(s)
                            #reset string
                            insertMe = " "
                    insertMe += "\n"
                    messages.tag_config("text",
                                        foreground=_from_rgb((204, 204, 204)))
                    messages.insert(END, insertMe, "text")
                    #print(mySlot)
                    if mySlot not in x:
                        #if its not our own input, no beep
                        window.title("Unread")
                        beep = mixer.Sound(resource_path(
                            "hitmarker.wav"))  #Loading File Into Mixer
                        beep.set_volume(0.02)
                        beep.play()  #Playing It In The Whole Device
                    if float(scroll_y.get()[1]) > 0.9:
                        messages.see("end")
                    messages.configure(state="disable")
        if win32gui.GetForegroundWindow() == winId:
            window.title("SoF Console")
        time.sleep(1)
Пример #23
0
import ctypes
ctypes.windll.user32.ShowWindow(ctypes.windll.kernel32.GetConsoleWindow(), 6)

if getattr(sys, 'frozen', False):
    app_path = os.path.dirname(sys.executable)
elif __file__:
    app_path = os.path.dirname(__file__)

import qtmodern.styles
import qtmodern.windows

#to build it using pyinstaller, replace the following line with the one after it

#FORM_CLASS,_=loadUiType(path.join(path.dirname(__file__), "main.ui"))
from main import Ui_MainWindow as FORM_CLASS
"""def callback(hwnd, pid):
  if win32process.GetWindowThreadProcessId(hwnd)[1] == pid:
    # hide window
    win32gui.ShowWindow(hwnd, 0)

# find hwnd of parent process, which is the cmd.exe window
win32gui.EnumWindows(callback, os.getppid())"""


#Supress Warning
def suppress_qt_warnings():
    environ["QT_DEVICE_PIXEL_RATIO"] = "0"
    environ["QT_AUTO_SCREEN_SCALE_FACTOR"] = "1"
    environ["QT_SCREEN_SCALE_FACTORS"] = "1"
    environ["QT_SCALE_FACTOR"] = str(ScaleFact)
Пример #24
0
            # Press q to quit
            if cv2.waitKey(250) & 0xFF == ord('q'):
                cv2.destroyAllWindows()
                break

        # Playback image movie from screencapture
        for img in img_matrix:
            cv2.imshow('Playback', img)
            time.sleep(0.1)


def callback(hwnd, extra):
    rect = win32gui.GetWindowRect(hwnd)
    x = int(rect[0] * 1.25)
    y = int(rect[1] * 1.25)
    w = int(rect[2] * 1.25) - x
    h = int(rect[3] * 1.25) - y
    text = win32gui.GetWindowText(hwnd)
    if text == "Old School RuneScape":
        print("Window %s:" % text)
        print("\tLocation: (%d, %d)" % (x, y))
        print("\t    Size: (%d, %d)" % (w, h))

        size = [int(w), int(h)]
        position = [x, y]
        monitor = {'top': y, 'left': x, 'width': size[0], 'height': size[1]}
        screenshot_and_draw(monitor)


win32gui.EnumWindows(callback, None)
Пример #25
0
 def find_window_wildcard(self, wildcard=PRODUCT_CONFIG['PRODUCT_NAME']):
     win32gui.EnumWindows(self._window_enum_callback, wildcard)
Пример #26
0
    def list_window_names():
        def winEnumHandler(hwnd, ctx):
            if win32gui.IsWindowVisible(hwnd):
                print(hex(hwnd), win32gui.GetWindowText(hwnd))

        win32gui.EnumWindows(winEnumHandler, None)
Пример #27
0
from win32 import win32gui


def EnumWindowsHandler(hwnd, extra):
    wintext = win32gui.GetWindowText(hwnd)
    if wintext and 'Everything' in wintext:
        print("%08X: %s" % (hwnd, wintext))
    else:
        return None


if __name__ == '__main__':
    win32gui.EnumWindows(EnumWindowsHandler, None)
Пример #28
0
 def find_window_wildcard(self, wildcard):
     self._handle = None
     win32gui.EnumWindows(self._window_enum_callback, wildcard)
Пример #29
0
    def find_window(cls, **kwargs):
        """
        查找指定的窗口

        @param {kwargs} - 具体实现类的扩展参数
            muti_search {bool} - 是否返回所有匹配结果,默认为False,仅返回第一个结果
            handle {int} - 窗口句柄, 如果指定该参数则直接获取该句柄的窗口, 不处理其他参数
            top_level_only {bool} - 仅限顶级元素(默认值=True), 如果指定该参数则仅使用class_name、name检索顶层窗口, 不处理其他参数
            class_name {str} - 窗口的类名(可通过spy++获取到)
            name {str} - 窗口标题
            depth {int} - 最大搜索深度(数量,默认值5000)
            class_name_re {str} - 类与此正则表达式匹配的元素
            name_re {str} - 文本与此正则表达式匹配的元素
            parent {int} - 父窗口对象(句柄或WindowControlSpec对象)
            process {int} - 窗口所在的应用进程对象(进程ID)
            visible_only {bool} - 仅可见元素 (默认值=False)
            enabled_only {bool} - 仅启用元素 (默认值=False)
            active_only {bool} - 仅限活动元素(默认= False)

        @returns {WindowControlSpec|list} - 返回窗口对象,如果muti_search为True则返回匹配到的窗口数组
        """
        # 默认参数处理
        _kwargs = {
            'muti_search': False,
            'class_name': None,
            'name': None,
            'depth': 5000,
            'top_level_only': True,
            'visible_only': False,
            'enabled_only': False,
            'active_only': False,
        }
        _kwargs.update(kwargs)

        # 直接给了窗口句柄,忽略其他条件
        if 'handle' in _kwargs.keys():
            if _kwargs['muti_search']:
                return [
                    WindowControlSpec(handle=kwargs['handle']),
                ]
            else:
                return WindowControlSpec(handle=kwargs['handle'])

        # 只查找顶级元素
        if _kwargs['top_level_only']:
            _hwnd = win32gui.FindWindow(_kwargs['class_name'], _kwargs['name'])
            if _hwnd == 0:
                if _kwargs['muti_search']:
                    return []
                else:
                    # 找不到窗口抛出异常
                    raise base_control.WindowException('Window not Found')

            if _kwargs['muti_search']:
                return [
                    WindowControlSpec(handle=_hwnd),
                ]
            else:
                return WindowControlSpec(handle=_hwnd)

        # 遍历方式查找
        _enum_para = {
            'search_para': _kwargs,  # 传入的匹配参数
            'current_depth': 0,  # 当前搜索数量
            'windows': []  # 存储返回的对象
        }

        if 'parent' in _kwargs.keys():
            # 有主窗口的情况
            try:
                win32gui.EnumChildWindows(_kwargs['parent'],
                                          cls._enum_windows_call_back,
                                          _enum_para)
            except:
                # 如果回调函数返回False,将会抛出异常,需要屏蔽处理
                pass
        else:
            # 从主窗口开始遍历查找
            try:
                win32gui.EnumWindows(cls._enum_windows_call_back, _enum_para)
            except:
                # 如果回调函数返回False,将会抛出异常,需要屏蔽处理
                pass

            # 再遍历查找子窗口
            if len(_enum_para['windows']) == 0 or _kwargs['muti_search']:
                _enum_para_child = {
                    'search_para': _kwargs,  # 传入的匹配参数
                    'current_depth': _enum_para['current_depth'],  # 当前搜索数量
                    'windows': []  # 存储返回的对象
                }
                for _win in _enum_para['windows']:
                    try:
                        win32gui.EnumChildWindows(_win.handle,
                                                  cls._enum_windows_call_back,
                                                  _enum_para_child)
                        if not _kwargs['muti_search'] and len(
                                _enum_para_child['windows']) > 0:
                            break
                    except:
                        # 如果回调函数返回False,将会抛出异常,需要屏蔽处理
                        pass

                # 合并两个数组
                _enum_para['windows'].extend(_enum_para_child['windows'])

        # 返回结果
        if _kwargs['muti_search']:
            return _enum_para['windows']
        else:
            if len(_enum_para['windows']) > 0:
                return _enum_para['windows'][0]
            else:
                # 找不到窗口抛出异常
                raise base_control.WindowException('Window not Found')
Пример #30
0
    monitor_dict["left"] = rw[0] + border_width
    monitor_dict["top"] = rw[1] + border_height + SM_HUD_HEIGHT
    # monitor_dict["width"] = rc[2] + 1
    monitor_dict["width"] = SM_SIZE[0]
    # monitor_dict["height"] = rc[3] - SM_HUD_HEIGHT
    monitor_dict["height"] = SM_SIZE[1] - SM_HUD_HEIGHT - CROP_BOTTOM


def callback(hwnd, monitor_dict):
    if win32gui.GetWindowText(hwnd) == "Snes9X v1.54.1 for Windows":
        monitor_dict["hwnd"] = hwnd
        track_window_position(monitor_dict)


monitor = {}
win32gui.EnumWindows(callback, monitor)
if not monitor:
    raise EOFError("couldn't find Snes9x")

#TODO: define a class for templates to check for and preload them
#template = cv2.imread("d/door_h.png", 0)
#th, tw = template.shape
"""img = cv2.imread("d/7.png", 0)  # (flag 0 returns a greyscale image) img is a numpy array
img2 = img.copy()  # ?
template = cv2.imread("d/door_h.png", 0)
h, w = template.shape
methods = ['cv2.TM_CCOEFF', 'cv2.TM_CCOEFF_NORMED', 'cv2.TM_CCORR',
            'cv2.TM_CCORR_NORMED', 'cv2.TM_SQDIFF', 'cv2.TM_SQDIFF_NORMED']"""

#https://stackoverflow.com/questions/35097837/capture-video-data-from-screen-in-python
#https://stackoverflow.com/questions/24129253/screen-capture-with-opencv-and-python-2-7