示例#1
0
def message_box(
    msg: Text,
    caption: Text,
    *,
    flags: int = 0,
    h_wnd: int = 0,
    on_close: Optional[Callable[[int], None]] = None,
) -> Callable[[], None]:
    def _run():
        res = win32gui.MessageBox(h_wnd, msg, caption, flags)
        if callable(on_close):
            on_close(res)

    t = threading.Thread(target=_run)
    t.start()
    h_wnd_set: Set[int] = set()

    def _iter_window(h_wnd: int, _: None):
        if win32gui.GetClassName(h_wnd) != "#32770":  # message box
            return
        h_wnd_set.add(h_wnd)

    assert t.ident is not None
    while not h_wnd_set:
        time.sleep(0.01)
        win32gui.EnumThreadWindows(t.ident, _iter_window, None)
    assert len(h_wnd_set) == 1, h_wnd_set

    def _close():
        for i in h_wnd_set:
            if win32gui.IsWindow(i):
                win32gui.PostMessage(i, win32con.WM_CLOSE, 0, 0)
        t.join()

    return _close
示例#2
0
def process_close(process, timeout: int = 10, cmd_filter: str = None):
    ''' Kills the process 'softly'. Returns 'True' if process
		was closed 'softly' and False if process was killed
		after timeout.
	'''
    def collect_windows(hwnd, param=None):
        nonlocal windows
        windows.append(hwnd)
        return True

    pid = process_get(process, cmd_filter)
    if not pid: return False
    windows = []
    try:
        for thread in psutil.Process(pid).threads():
            win32gui.EnumThreadWindows(thread.id, collect_windows, None)
    except psutil.NoSuchProcess:
        dev_print('process is gone')
        pass
    for hwnd in windows:
        try:
            win32gui.PostMessage(hwnd, win32con.WM_CLOSE, 0, 0)
        except Exception as e:
            dev_print(f'postmessage error: {repr(e)}')
    for _ in range(timeout):
        time.sleep(1)
        if not psutil.pid_exists(pid): return True
    try:
        psutil.Process(pid).kill()
    except ProcessLookupError:
        dev_print(f'PID {pid} was not found')
    return False
示例#3
0
def find_windows(thread_id=None,
                 process_id=None,
                 parent_hwnd=None,
                 class_name=None,
                 window_text=None,
                 stop_if_found=True):
    """
    Find top level windows matching certain criteria
    :param process_id: only match windows that belong to this process id if specified
    :param class_name: only match windows that match this class name if specified
    :param window_text: only match windows that match this window text if specified
    :param stop_if_found: stop when find a match
    :returns: list of window handles found by search
    """
    found_hwnds = []

    # sub-function used to actually enumerate the windows in EnumWindows
    def enum_windows_proc(hwnd, lparam):
        # print "Window name: %s" % safe_get_window_text(hwnd)
        # print "Window class: %s" % win32gui.GetClassName(hwnd)
        # print "Window process id: %s" % win32process.GetWindowThreadProcessId(hwnd)[1]

        # try to match process id:
        if process_id != None:
            _, win_process_id = win32process.GetWindowThreadProcessId(hwnd)
            if win_process_id != process_id:
                return True

        # try to match class name:
        if class_name != None and (win32gui.GetClassName(hwnd) != class_name):
            return True

        # try to match window text:
        matches_window_text = True
        if window_text != None and (window_text
                                    not in safe_get_window_text(hwnd)):
            return True

        # found a match
        found_hwnds.append(hwnd)

        return not stop_if_found

    # enumerate all top-level windows:
    try:
        if parent_hwnd != None:
            win32gui.EnumChildWindows(parent_hwnd, enum_windows_proc, None)
        elif thread_id != None:
            win32gui.EnumThreadWindows(thread_id, enum_windows_proc, None)
        else:
            win32gui.EnumWindows(enum_windows_proc, None)
    except:
        # stupid api!
        pass

    return found_hwnds
示例#4
0
def get_error_hwnd(threadid):
    param_list = []
    param_list.append('TErrorBoxForm')
    param_list.append('')

    try:
        win32gui.EnumThreadWindows(threadid, processenum, param_list)
        return param_list[1]
    except:
        return param_list[1]
示例#5
0
 def getwindow(self):
     """
     Gets the window handle for the window named 'rfoil01Graphic' in the
     given process.
     """
     while 'rfoil01Graphic' not in self.handle:
         time.sleep(0.1)
         try:
             win32gui.EnumThreadWindows(self.tid, self.wcallb, self.handle)
         except:
             pass
示例#6
0
def main():
    # proc = subprocess.Popen("C:\\Program Files (x86)\\Leap Motion\\Core Services\\VisualizerApp.exe", stdin=subprocess.PIPE, stderr=subprocess.STDOUT)
    # time.sleep(1)
    # try:
    #     proc.stdin.write(b'f')
    # except:
    #     print("Killing")
    #     proc.kill()
    _, cmd = win32api.FindExecutable('"C:\\Program Files (x86)\\Leap Motion\\Core Services\\VisualizerApp.exe"')
    time.sleep(1)
    _, _, pid, tid = win32process.CreateProcess(
        None,    # name
        cmd,     # command line
        None,    # process attributes
        None,    # thread attributes
        0,       # inheritance flag
        0,       # creation flag
        None,    # new environment
        None,    # current directory
        win32process.STARTUPINFO ())
    def wcallb(hwnd, handle):
        handle[win32gui.GetClassName(hwnd)] = hwnd
        win32gui.EnumChildWindows(hwnd, wcallb, handle)
        return True
    handle = {}
    while not handle:   # loop until the window is loaded
        time.sleep(0.5)
        win32gui.EnumThreadWindows(tid, wcallb, handle)
    win32api.PostMessage(
    handle['FREEGLUT'],
    win32con.WM_CHAR,
    ord("f"),
    0)
    # Create a sample listener and controller
    listener = SampleListener()
    controller = Leap.Controller()
    listener.add_handle(handle)

    # Have the sample listener receive events from the controller
    controller.add_listener(listener)

    # Keep this process running until Enter is pressed
    print("Press Enter to quit...")
    sys.stdout.flush()
    try:
        sys.stdin.readline()
    except KeyboardInterrupt:
        pass
    finally:
        # Remove the sample listener when done
        controller.remove_listener(listener)
示例#7
0
def get_sure_hwnd(threadid):
    param_list = []
    param_list.append('TImageCodeForm')
    param_list.append('')

    if _test_env:
        param_list[0] = 'TImageForm'

    while True:
        time.sleep(0.2)
        try:
            win32gui.EnumThreadWindows(threadid, processenum, param_list)
            if param_list[1]:
                return param_list[1]
        except:
            if param_list[1]:
                return param_list[1]
示例#8
0
def PopulateWindowHandler(hwnd, data):
    name = win32gui.GetWindowText(hwnd)
    isWindow = win32gui.IsWindow(hwnd)
    if not not name and isWindow:
        osHandlerModel = OsHandlerModel.OsHandlerModel(data[1], hwnd, name,
                                                       data[2])
        if data[1] > 0:
            try:
                if data[0]:
                    win32gui.EnumChildWindows(
                        hwnd, PopulateWindowHandler,
                        (data[0], data[1] - 1, osHandlerModel))
                else:
                    win32gui.EnumThreadWindows(
                        hwnd, PopulateWindowHandler,
                        (data[0], data[1] - 1, osHandlerModel))
            except:
                pass
        data[2].addChild(osHandlerModel)
示例#9
0
    def get_result(self):
        tid, pid = win32process.GetWindowThreadProcessId(self.hwnd_main)

        def enum_children(hwnd, results):
            try:
                if (win32gui.IsWindowVisible(hwnd)
                        and win32gui.IsWindowEnabled(hwnd)):
                    win32gui.EnumChildWindows(hwnd, handler, results)
            except Exception:
                return

        def handler(hwnd, results):
            if (win32api.GetWindowLong(hwnd, win32con.GWL_ID) == 0x3EC
                    and win32gui.GetClassName(hwnd) == 'Static'):
                results.append(hwnd)
                return False
            enum_children(hwnd, results)
            return len(results) == 0

        popups = []
        windows = []
        win32gui.EnumThreadWindows(tid, lambda hwnd, l: l.append(hwnd),
                                   windows)
        for hwnd in windows:
            if not handler(hwnd, popups):
                break
        if popups:
            ctrl = popups[0]
            text = get_text(ctrl)
            if u'已成功提交' in text:
                return {
                    'code': 0,
                    'status': 'succeed',
                    'msg': text,
                    'entrust_no': text.split(u'合同编号:')[1].split('。')[0],
                }
            else:
                return {
                    'code': 1,
                    'status': 'failed',
                    'msg': text,
                }
示例#10
0
def get_sidebar_hwnd(title):
    hwnd = get_window_hwnd(title)
    cur_tid, cur_pid = win32process.GetWindowThreadProcessId(hwnd)

    def callback(hwnd, info):
        tid, pid = win32process.GetWindowThreadProcessId(hwnd)
        if pid != info["pid"]:
            return True
        text = win32gui.GetWindowText(hwnd)
        if text != "通过键盘调节GPS方位和移动速度":
            return True
        rect = win32gui.GetWindowRect(hwnd)
        size = (rect[2] - rect[0], rect[3] - rect[1])
        if size != (40, 754):
            return True
        info["found"] = hwnd
        return False

    info = {"tid": cur_tid, "pid": cur_pid, "found": []}
    try:
        win32gui.EnumThreadWindows(cur_tid, callback, info)
    except:
        pass
    return info["found"]