Beispiel #1
0
def activate_by_attach(hwnd):
    import win32process
    import win32api
    import win32gui
    import ctypes

    forehwnd = win32gui.GetForegroundWindow()
    fore_threadid, processid = win32process.GetWindowThreadProcessId(forehwnd)
    current_threadid = win32api.GetCurrentThreadId()

    # foreground なスレッドにアタッチする
    if fore_threadid != current_threadid:
        try:
            # たまに error:87 が起きるので吸収.
            win32process.AttachThreadInput(current_threadid, fore_threadid,
                                           True)
        except:
            pass

    try:
        ctypes.windll.user32.BringWindowToTop(hwnd)
    except:
        pass

    if fore_threadid != current_threadid:
        try:
            win32process.AttachThreadInput(current_threadid, fore_threadid,
                                           False)
        except:
            pass
Beispiel #2
0
def main():
    # メモ帳の起動
    subprocess.Popen(r'notepad.exe')

    # 起動するまで待機
    time.sleep(1)

    # 起動したメモ帳のハンドルを取得する。
    hw1 = win32gui.GetForegroundWindow()
    print(hw1)
    tid1 = win32process.GetWindowThreadProcessId(hw1)

    # ウェイトして他プロセスをアクティブにしておく。
    time.sleep(10)

    # アクティブにした他プロセスのハンドルを取得する。
    hw2 = win32gui.GetForegroundWindow()
    print(hw2)
    tid2 = win32process.GetWindowThreadProcessId(hw2)

    # トップレベルウィンドウを切り替える(この時点ではフォーカスできていない)
    win32process.AttachThreadInput(tid1, tid2, True)
    win32gui.BringWindowToTop(hw1)
    win32process.AttachThreadInput(tid1, tid2, False)

    # ウィンドウの左上の隅っこをクリックしてアクティブにする。
    (left, top, right, bottom) = win32gui.GetWindowRect(hw1)
    print(left, top, right, bottom)
    win32api.SetCursorPos((left + 1, top + 1))
    time.sleep(0.1)
    win32api.mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0)
    time.sleep(0.1)
    win32api.mouse_event(MOUSEEVENTF_LEFTUP, 0, 0)
Beispiel #3
0
 def getCurrentCursor(whandle):
     pid = win32process.GetWindowThreadProcessId(whandle)[0]
     tid = win32api.GetCurrentThreadId()
     win32process.AttachThreadInput(pid, tid, True)
     crsr = win32gui.GetCursor()
     win32process.AttachThreadInput(pid, tid, False)
     return crsr
Beispiel #4
0
 def GetFocus(cls):
     curtid = win32api.GetCurrentThreadId()
     whd = win32gui.GetForegroundWindow()
     (tid, pid) = win32process.GetWindowThreadProcessId(whd)
     win32process.AttachThreadInput(curtid, tid, True)
     focus_whd = win32gui.GetFocus()
     win32process.AttachThreadInput(curtid, tid, False)
     return focus_whd
Beispiel #5
0
    def set_focus(self):
        """
        Set the focus to this control.

        Bring the window to the foreground first if necessary.
        """
        # find the current foreground window
        cur_foreground = win32gui.GetForegroundWindow()

        # if it is already foreground then just return
        if self.handle != cur_foreground:
            # set the foreground window

            # get the thread of the window that is in the foreground
            cur_fore_thread = win32process.GetWindowThreadProcessId(
                cur_foreground)[0]

            # get the thread of the window that we want to be in the foreground
            control_thread = win32process.GetWindowThreadProcessId(
                self.handle)[0]

            # if a different thread owns the active window
            if cur_fore_thread != control_thread:
                # Attach the two threads and set the foreground window
                win32process.AttachThreadInput(control_thread, cur_fore_thread,
                                               1)

                win32gui.SetForegroundWindow(self.handle)

                # ensure foreground window has changed to the target
                # or is 0(no foreground window) before the threads detaching
                timings.WaitUntil(
                    Timings.setfocus_timeout, Timings.setfocus_retry,
                    lambda: win32gui.GetForegroundWindow(
                    ) in [self.top_level_parent().handle, 0])

                # get the threads again to check they are still valid.
                cur_fore_thread = win32process.GetWindowThreadProcessId(
                    cur_foreground)[0]
                control_thread = win32process.GetWindowThreadProcessId(
                    self.handle)[0]

                if cur_fore_thread and control_thread:  # both are valid
                    # Detach the threads
                    win32process.AttachThreadInput(control_thread,
                                                   cur_fore_thread, 0)
            else:
                # same threads - just set the foreground window
                win32gui.SetForegroundWindow(self.handle)

            # make sure that we are idle before returning
            win32functions.WaitGuiThreadIdle(self)

            # only sleep if we had to change something!
            time.sleep(Timings.after_setfocus_wait)

        return self
Beispiel #6
0
def press_code_on_ths(hwnd_ths, code='002531'):
    win32gui.PostMessage(hwnd_ths, win32con.WM_KEYDOWN, ord('6') & 0xFF, 0)
    win32gui.PostMessage(hwnd_ths, win32con.WM_KEYUP, ord('6') & 0xFF, 0)
    time.sleep(0.3)
    win32gui.SetForegroundWindow(hwnd_ths)
    self_thread_id = win32api.GetCurrentThreadId()
    fore_thread_id = win32process.GetWindowThreadProcessId(hwnd_ths)
    win32process.AttachThreadInput(fore_thread_id[0], self_thread_id, True)
    obj_wnd = win32gui.GetFocus()
    win32gui.SendMessage(obj_wnd, win32con.WM_SETTEXT, 0, code)
    win32gui.PostMessage(obj_wnd, win32con.WM_KEYDOWN, win32con.VK_RETURN, 0)
    win32gui.PostMessage(obj_wnd, win32con.WM_KEYUP, win32con.VK_RETURN, 0)
    win32process.AttachThreadInput(fore_thread_id[0], self_thread_id, False)
    return True
Beispiel #7
0
 def __exit__(self, unused_type, unused_value, unused_traceback):
     """Detaches the current thread from the active thread's message queue."""
     if not self._active_thread_id:
         return
     current_thread_id = win32api.GetCurrentThreadId()
     win32process.AttachThreadInput(current_thread_id,
                                    self._active_thread_id, 0)
     logging.info('Detached current thread input %s from thread: %s',
                  current_thread_id, self._active_thread_id)
Beispiel #8
0
def _old(hwnd):
    """So ugly here..."""
    if not win32gui.IsWindow(hwnd):
        return


    fgwin = win32gui.GetForegroundWindow()
    fg, fp = win32process.GetWindowThreadProcessId(fgwin)
    current = win32api.GetCurrentThreadId()

    try:
        attached = False
        if current != fg and fg:
            try:
                attached = win32process.AttachThreadInput(fg, current, True)
            except:
                pass
            #AllowSetForegroundWindow(ASFW_ANY)
        _, showCmd, _, _, _ = win32gui.GetWindowPlacement(hwnd)
        # to show window owned by admin process when running in user process
        # see http://msdn.microsoft.com/en-us/library/windows/desktop/ms633548(v=vs.85).aspx
        # for details
        if showCmd == SW_SHOWMINIMIZED:
            #win32gui.ShowWindow(hwnd, SW_RESTORE)
            win32api.SendMessage(hwnd, win32con.WM_SYSCOMMAND, win32con.SC_RESTORE, 0)
        else:
            #win32gui.ShowWindow(hwnd, SW_SHOW)
            win32api.SendMessage(hwnd, win32con.WM_SYSCOMMAND, win32con.SW_SHOW, 0)

        for fn in [
            win32gui.BringWindowToTop,
            win32gui.SetForegroundWindow,
            win32gui.SetActiveWindow,
            win32gui.SetFocus
        ]:
            try:
                fn(hwnd)
            except Exception as e:
                logging.error(str(e))
    except Exception as e:
        logging.error(str(e))
    finally:
        if attached:
            win32process.AttachThreadInput(fg, win32api.GetCurrentThreadId(), False)
Beispiel #9
0
def set_focus_window(hdl):
    '''
    Set the game window to focus and then we can do next jobs.
    '''
    tid, pid = win32process.GetWindowThreadProcessId(hdl)
    m_tid = win32api.GetCurrentThreadId()

    try:
        win32process.AttachThreadInput(m_tid, tid, -1)
        win32gui.BringWindowToTop(hdl)
        shell = win32com.client.Dispatch('WScript.Shell')
        shell.SendKeys('%')

        win32gui.SetForegroundWindow(hdl)
        win32gui.SetFocus(hdl)
    except Exception as e:
        print(e)
        print('Can not set focus')
    win32process.AttachThreadInput(m_tid, tid, 0)
    def get_caret(self):
        # get current caret position within window

        res = (-1, -1)  # failure value

        fg_win = win32gui.GetForegroundWindow(
        )  # find the current foreground window
        fg_thread, fg_process = win32process.GetWindowThreadProcessId(
            fg_win)  # get thread and process information
        current_thread = win32api.GetCurrentThreadId(
        )  # find the current thread
        win32process.AttachThreadInput(current_thread, fg_thread,
                                       True)  # attach to the current thread
        try:
            res = win32gui.GetCaretPos()  # find the caret
        finally:
            win32process.AttachThreadInput(
                current_thread, fg_thread,
                False)  # and always detatch from the other thread

        return res  # and this is where the text cursor is
Beispiel #11
0
    def set_foreground_window(self):
        if win32gui.GetForegroundWindow() != self.hwnd:
            mtid, mpid = win32process.GetWindowThreadProcessId(
                win32gui.GetForegroundWindow())
            tid, pid = win32process.GetWindowThreadProcessId(self.hwnd)
            if mtid != tid:
                win32process.AttachThreadInput(mtid, tid, 1)
                win32gui.SetForegroundWindow(self.hwnd)
#            win32gui.SetFocus(hwnd)
#                win32process.AttachThreadInput(mtid, tid, FALSE)
            else:
                win32gui.SetForegroundWindow(self.hwnd)
def ActivateWindow(hwnd):
    """
    指定ウィンドウをアクティブにする.
    """
    foreground_threadid, processid = \
        win32process.GetWindowThreadProcessId(
            GetForegroundWindow()
        )
    current_threadid = win32api.GetCurrentThreadId()

    # foreground なスレッドにアタッチする
    if foreground_threadid != current_threadid:
        try:
            # たまに error:87 が起きるので吸収.
            # @todo error:87 の原因調査
            win32process.AttachThreadInput(
                current_threadid,
                foreground_threadid,
                True
            )
        except:
            pass

    try:
        # ウィンドウハンドルが無効だとエラーになる(code:1400)ので
        # ここで吸収.
        win32gui.SetForegroundWindow(hwnd)
    except:
        pass

    # アタッチしていればデタッチする..
    if foreground_threadid != current_threadid:
        try:
            win32process.AttachThreadInput(
                current_threadid,
                foreground_threadid,
                False
            )
        except:
            pass
Beispiel #13
0
    def set_property(self, element, propertyName, value):
        validProperties = ['TEXT', 'FOCUS', 'ACTIVE']
        name = propertyName.upper()
        if name not in validProperties:
            raise ValueError('%s not supported!' % name)
        if name == 'FOCUS' and value is True:
            current_id = win32api.GetCurrentThreadId()
            target_id = win32process.GetWindowThreadProcessId(element)[0]
            win32process.AttachThreadInput(target_id, current_id, True)
            win32gui.SetFocus(element)
            win32process.AttachThreadInput(target_id, current_id, False)
        elif name == 'TEXT':
            pass
        elif name == 'active' and value is True:
            fwnd = win32gui.GetForegroundWindow()
            if fwnd == element:
                return
            if fwnd == 0:
                try:
                    win32gui.SetForegroundWindow(element)
                    return
                except win32api.error:
                    # 防止有菜单弹出导致异常
                    Keyboard.input_keys('{ESC}')
                    win32gui.SetForegroundWindow(element)
                    return

            ftid, _ = win32process.GetWindowThreadProcessId(fwnd)
            wtid, _ = win32process.GetWindowThreadProcessId(element)

            ctypes.windll.user32.AttachThreadInput(wtid, ftid, True)
            st = time.time()
            while (time.time() - st) < 5:
                if win32gui.GetForegroundWindow() == element:
                    break
                ctypes.windll.user32.SetForegroundWindow(element)
                time.sleep(0.5)

            ctypes.windll.user32.AttachThreadInput(wtid, ftid, False)
Beispiel #14
0
def setAppWindowForeground(Appname, windowsize=3):  # 让特定程序获得焦点
    hForeWnd = win32gui.GetForegroundWindow()
    dwCurID = win32api.GetCurrentThreadId()
    dwForeID = win32process.GetWindowThreadProcessId(hForeWnd)

    windowHandle = win32gui.FindWindow(0, Appname)
    if hForeWnd != 0 and dwCurID != dwForeID[0]:
        win32process.AttachThreadInput(dwCurID, dwForeID[0], True)
    # 参数解释https://msdn.microsoft.com/en-us/library/windows/desktop/ms633548(v=vs.85).aspx
    win32gui.ShowWindow(windowHandle, windowsize)
    win32gui.SetWindowPos(windowHandle, -1, 0, 0, 0, 0, 0x0001 | 0x0002)
    win32gui.SetWindowPos(windowHandle, -2, 0, 0, 0, 0, 0x0001 | 0x0002)
    if hForeWnd != 0:
        win32gui.SetForegroundWindow(windowHandle)
Beispiel #15
0
    def __enter__(self):
        """Attaches the current thread to the foreground window's message queue.

    This is an old and well known exploit used to bypass Windows Focus rules:
    http://www.google.com/search?q=attachthreadinput+setforegroundwindow
    """
        self._active_thread_id = 0
        active_hwnd = win32gui.GetForegroundWindow()
        if not active_hwnd:
            logging.warning('No active window is found.')
            return
        current_thread_id = win32api.GetCurrentThreadId()
        active_thread_id, _ = win32process.GetWindowThreadProcessId(
            active_hwnd)
        win32process.AttachThreadInput(current_thread_id, active_thread_id, 1)
        logging.info('Attached current thread input %s to active thread: %s',
                     current_thread_id, active_thread_id)
        self._active_thread_id = active_thread_id
    def switch_active_monitor(self, show_cam=False, show_spf=False):
        # Webcam setup
        cap = cv2.VideoCapture(0)
        cap_width = cap.get(cv2.CAP_PROP_FRAME_WIDTH)
        cap_height = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)
        width_factor = cap_width / self.width
        height_factor = cap_height / self.height

        # Get monitors' IDs
        p_mon_id = int(win32api.EnumDisplayMonitors()[0][0])
        s_mon_id = int(win32api.EnumDisplayMonitors()[1][0])

        # Get thread's ID
        cur_thread_id = win32api.GetCurrentThreadId()

        with tf.Session() as sess:
            init = tf.global_variables_initializer()
            sess.run(init)
            saver = tf.train.Saver()
            save_dir = "checkpoints"
            save_path = os.path.join(save_dir, "model.ckpt")
            saver.save(sess, save_path)
            flag, frame = cap.read()

            while flag:
                if show_spf:
                    startime = time.time()

                orig_image = frame
                frame = cv2.resize(frame, (self.width, self.height))
                frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
                frame = frame.astype(float)
                frame = frame * (2.0 / 255.0) - 1.0
                frame = np.array(frame, dtype=np.float32)
                frame = frame.reshape(1, self.width, self.height, 3)
                (
                    heatmaps_result,
                    offsets_result,
                    displacementFwd_result,
                    displacementBwd_result,
                ) = sess.run(
                    [
                        self.heatmaps,
                        self.offsets,
                        self.displacementFwd,
                        self.displacementBwd,
                    ],
                    feed_dict={self.image: frame},
                )
                poses = decode_single_pose(heatmaps_result, offsets_result, 16,
                                           width_factor, height_factor)

                if show_spf:
                    endtime = time.time()
                    print("Time cost per frame : %f" % (endtime - startime))

                # Calculate the distance between nose and shoulders
                nose_pos = poses[0]["keypoints"][0]["position"]
                nose_pos_array = np.array((nose_pos["x"], nose_pos["y"]))
                lshoulder_pos = poses[0]["keypoints"][5]["position"]
                lshoulder_pos_array = np.array(
                    (lshoulder_pos["x"], lshoulder_pos["y"]))
                rshoulder_pos = poses[0]["keypoints"][6]["position"]
                rshoulder_pos_array = np.array(
                    (rshoulder_pos["x"], rshoulder_pos["y"]))
                ldiff = nose_pos_array - lshoulder_pos_array
                ldist = np.linalg.norm(ldiff)
                rdiff = nose_pos_array - rshoulder_pos_array
                rdist = np.linalg.norm(rdiff)

                # Get active monitor's ID
                win_id = win32gui.GetForegroundWindow()
                act_mon_id = int(win32api.MonitorFromWindow(win_id, 2))

                if act_mon_id == p_mon_id:
                    if win_id != 0:
                        p_mon_win = win_id

                    if rdist < ldist:
                        try:
                            win_thread_id, _ = win32process.GetWindowThreadProcessId(
                                s_mon_win)
                            win32process.AttachThreadInput(
                                cur_thread_id, win_thread_id, True)
                            win32gui.SetFocus(s_mon_win)
                            win32gui.SetForegroundWindow(s_mon_win)

                        except Exception:
                            pass

                elif act_mon_id == s_mon_id:
                    if win_id != 0:
                        s_mon_win = win_id

                    if rdist >= ldist:
                        try:
                            win_thread_id, _ = win32process.GetWindowThreadProcessId(
                                p_mon_win)
                            win32process.AttachThreadInput(
                                cur_thread_id, win_thread_id, True)
                            win32gui.SetFocus(p_mon_win)
                            win32gui.SetForegroundWindow(p_mon_win)

                        except Exception:
                            pass

                else:
                    raise Exception()

                if show_cam:
                    for i, _ in enumerate(poses):
                        if poses[i]["score"] > 0.2:
                            color = self.color_table[i]
                            drawKeypoints(poses[i], orig_image, color)
                            drawSkeleton(poses[i], orig_image)

                    cv2.imshow("1", orig_image)

                cv2.waitKey(1)
                flag, frame = cap.read()
Beispiel #17
0
import win32process
import win32api
import numpy as np
from array import array
from time import sleep
from win32api import GetSystemMetrics
import sqlite3
import math

l=0
#take user input
x=[]
fg_win = win32gui.GetForegroundWindow()
fg_thread, fg_process = win32process.GetWindowThreadProcessId(fg_win)
current_thread = win32api.GetCurrentThreadId()
win32process.AttachThreadInput(current_thread, fg_thread, True)
m=np.ndarray(shape=(GetSystemMetrics (0),GetSystemMetrics (1)),dtype=int)
while True:    
    l=l+1
    sleep(1)
    m[win32gui.GetCursorPos()[0],win32gui.GetCursorPos()[1]]=m[win32gui.GetCursorPos()[0],win32gui.GetCursorPos()[1]]+1
    if l==60*n:        
    	for x in range(0, m.shape[0]):
        	for y in range(0, m.shape[1]):
                    	if m[x, y] ==1:
                            	m[x, y] = 0
                            	
conn = sqlite3.connect('c:\\users\shengyu\\desktop\\stat.db')
c = conn.cursor()
for row in c.execute('select map from mousemap'):
    if l==0:
Beispiel #18
0
def mouse_pro(nCode, wParam, lParam):
    print('mouse_pro')
    """
    函数功能:鼠标钩子函数,当有鼠标事件,此函数被回调
    """
    if nCode == win32con.HC_ACTION:
        MSLLHOOKSTRUCT_p = POINTER(MSLLHOOKSTRUCT)
        param = cast(lParam, MSLLHOOKSTRUCT_p)
        # 鼠标左键点击
        if wParam == win32con.WM_LBUTTONDOWN:
            hForeWnd = win32gui.GetForegroundWindow()
            dwSelfThreadId = win32api.GetCurrentThreadId()
            print(dwSelfThreadId)
            dwForeThreadId = win32process.GetWindowThreadProcessId(hForeWnd)
            print(dwForeThreadId)
            win32process.AttachThreadInput(dwForeThreadId[1], dwSelfThreadId, True)
            hw = win32api.GetFocus()
            win32process.AttachThreadInput(dwForeThreadId[1], dwSelfThreadId, False)
            # hw = win32gui.WindowFromPoint(win32api.GetCursorPos())

            print("%s#######################%s" % (hw, mouse_hd))
            print(win32gui.GetClassName(hw))
            left, top, right, bottom = win32gui.GetWindowRect(hw)
            print(left, top, right, bottom)
            windowDc = win32gui.GetWindowDC(hw)
            if windowDc:
                prevPen = win32gui.SelectObject(windowDc, rectanglePen)
                prevBrush = win32gui.SelectObject(windowDc, win32gui.GetStockObject(win32con.HOLLOW_BRUSH))

                win32gui.Rectangle(windowDc, 0, 0, right - left, bottom - top)
                win32gui.SelectObject(windowDc, prevPen)
                win32gui.SelectObject(windowDc, prevBrush)
                win32gui.ReleaseDC(hw, windowDc)

            # hw = win32gui.WindowFromPoint((int(param.contents.pt.x),int(param.contents.pt.y)))
            # print("%s#######################%s" % (hw, mouse_hd))
            # print(win32gui.GetClassName(hw))
            # left, top, right, bottom = win32gui.GetWindowRect(hw)
            # print(left, top, right, bottom)
            # print("左键点击,坐标:x:%d,y:%d" % (param.contents.pt.x,param.contents.pt.y))
            # hwndChildList = get_child_windows(hw)
            # for hwndChild in hwndChildList:
            #     hw = hwndChild
            #     print("%s#######################%s" % (hw, mouse_hd))
            #     print(win32gui.GetClassName(hw))
            #     left, top, right, bottom = win32gui.GetWindowRect(hw)
            #     print(left, top, right, bottom)
            #     windowDc = win32gui.GetWindowDC(hw)
            #     if windowDc:
            #         prevPen = win32gui.SelectObject(windowDc, rectanglePen)
            #         prevBrush = win32gui.SelectObject(windowDc, win32gui.GetStockObject(win32con.HOLLOW_BRUSH))
            #
            #         win32gui.Rectangle(windowDc, 0, 0, right - left, bottom - top)
            #         win32gui.SelectObject(windowDc, prevPen)
            #         win32gui.SelectObject(windowDc, prevBrush)
            #         win32gui.ReleaseDC(hw, windowDc)

        # elif wParam == win32con.WM_LBUTTONUP:
        #     print("左键抬起,坐标:x:%d,y:%d" % (param.contents.pt.x, param.contents.pt.y))
        # elif wParam == win32con.WM_MOUSEMOVE:
        #     hw = win32gui.WindowFromPoint(win32api.GetCursorPos())
        #     print("%s#######################%s" % (hw, mouse_hd))
        #     print(win32gui.GetClassName(hw))
        #     left, top, right, bottom = win32gui.GetWindowRect(hw)
        #     print(left, top, right, bottom)
        #     windowDc = win32gui.GetWindowDC(hw)
        #     if windowDc:
        #         prevPen = win32gui.SelectObject(windowDc, rectanglePen)
        #         prevBrush = win32gui.SelectObject(windowDc, win32gui.GetStockObject(win32con.HOLLOW_BRUSH))
        #
        #         win32gui.Rectangle(windowDc, 0, 0, right - left, bottom - top)
        #         win32gui.SelectObject(windowDc, prevPen)
        #         win32gui.SelectObject(windowDc, prevBrush)
        #         win32gui.ReleaseDC(hw, windowDc)
        #
        #     # hw = win32gui.WindowFromPoint((int(param.contents.pt.x),int(param.contents.pt.y)))
        #     # print("%s#######################%s" % (hw, mouse_hd))
        #     # print(win32gui.GetClassName(hw))
        #     # left, top, right, bottom = win32gui.GetWindowRect(hw)
        #     # print(left, top, right, bottom)
        #
        #     print("鼠标移动,坐标:x:%d,y:%d" % (param.contents.pt.x, param.contents.pt.y))
        # elif wParam == win32con.WM_RBUTTONDOWN:
        #     print("右键点击,坐标:x:%d,y:%d" % (param.contents.pt.x, param.contents.pt.y))
        # elif wParam == win32con.WM_RBUTTONUP:
        #     print("右键抬起,坐标:x:%d,y:%d" % (param.contents.pt.x, param.contents.pt.y))
    return CallNextHookEx(mouse_hd, nCode, wParam, lParam)
Beispiel #19
0
        # print('cann\'t find 同花顺')
        break
    if win32gui.IsWindowVisible(hwndChild):
        win_text = win32gui.GetWindowText(hwndChild)
        # print(win_text[0:3])
        if win_text[0:3] == '同花顺':
            break

print(hwndChild)
if hwndChild != 0:
    print(
        win32gui.PostMessage(hwndChild, win32con.WM_KEYDOWN,
                             ord('6') & 0xFF, 0))
    print(
        win32gui.PostMessage(hwndChild, win32con.WM_KEYUP,
                             ord('6') & 0xFF, 0))
    time.sleep(0.3)
    win32gui.SetForegroundWindow(hwndChild)
    self_thread_id = win32api.GetCurrentThreadId()
    fore_thread_id = win32process.GetWindowThreadProcessId(hwndChild)
    print(self_thread_id, fore_thread_id)
    print(
        win32process.AttachThreadInput(fore_thread_id[0], self_thread_id,
                                       True))
    objwnd = win32gui.GetFocus()
    str = '600030'
    win32gui.SendMessage(objwnd, win32con.WM_SETTEXT, 0, str)
    win32gui.PostMessage(objwnd, win32con.WM_KEYDOWN, win32con.VK_RETURN, 0)
    win32gui.PostMessage(objwnd, win32con.WM_KEYUP, win32con.VK_RETURN, 0)
    win32process.AttachThreadInput(fore_thread_id[0], self_thread_id, False)
Beispiel #20
0
    def _force_set_foreground_window(self, hWindow):
        # As there are some restrictions about which processes can call SetForegroundWindow as described here:
        # https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-setforegroundwindow
        # we try consecutively three different ways to show the splash screen on top of all other windows.

        # Solution 1: Pressing alt key unlocks SetForegroundWindow
        # https://stackoverflow.com/questions/14295337/win32gui-setactivewindow-error-the-specified-procedure-could-not-be-found
        # Not using win32com.client.Dispatch like in the link because there are problems when building with py2exe.
        ALT_KEY = win32con.VK_MENU
        RIGHT_ALT = 0xb8
        win32api.keybd_event(ALT_KEY, RIGHT_ALT, 0, 0)
        win32api.keybd_event(ALT_KEY, RIGHT_ALT, win32con.KEYEVENTF_KEYUP, 0)
        win32gui.ShowWindow(hWindow, win32con.SW_SHOW)
        try:
            win32gui.SetForegroundWindow(hWindow)
        except Exception as e:
            exc_message = str(e)
            logger.debug(
                'Failed attempt to show splash screen with keybd_event: {}'.
                format(exc_message))

        if win32gui.GetForegroundWindow() == hWindow:
            return True

        # Solution 2: Attaching current thread to the foreground thread in order to use BringWindowToTop
        # https://shlomio.wordpress.com/2012/09/04/solved-setforegroundwindow-win32-api-not-always-works/
        foreground_thread_id, foreground_process_id = win32process.GetWindowThreadProcessId(
            win32gui.GetForegroundWindow())
        appThread = win32api.GetCurrentThreadId()

        if foreground_thread_id != appThread:

            try:
                win32process.AttachThreadInput(foreground_thread_id, appThread,
                                               True)
                win32gui.BringWindowToTop(hWindow)
                win32gui.ShowWindow(hWindow, win32con.SW_SHOW)
                win32process.AttachThreadInput(foreground_thread_id, appThread,
                                               False)
            except Exception as e:
                exc_message = str(e)
                logger.debug(
                    'Failed attempt to show splash screen with AttachThreadInput: {}'
                    .format(exc_message))

        else:
            win32gui.BringWindowToTop(hWindow)
            win32gui.ShowWindow(hWindow, win32con.SW_SHOW)

        if win32gui.GetForegroundWindow() == hWindow:
            return True

        # Solution 3: Working with timers that lock/unlock SetForegroundWindow
        #https://gist.github.com/EBNull/1419093
        try:
            timeout = win32gui.SystemParametersInfo(
                win32con.SPI_GETFOREGROUNDLOCKTIMEOUT)
            win32gui.SystemParametersInfo(
                win32con.SPI_SETFOREGROUNDLOCKTIMEOUT, 0,
                win32con.SPIF_SENDCHANGE)
            win32gui.BringWindowToTop(hWindow)
            win32gui.SetForegroundWindow(hWindow)
            win32gui.SystemParametersInfo(
                win32con.SPI_SETFOREGROUNDLOCKTIMEOUT, timeout,
                win32con.SPIF_SENDCHANGE)
        except Exception as e:
            exc_message = str(e)
            logger.debug(
                'Failed attempt to show splash screen with SystemParametersInfo: {}'
                .format(exc_message))

        if win32gui.GetForegroundWindow() == hWindow:
            return True

        # Solution 4: If on some machines the splash screen still doesn't come on top, we can try
        # the following solution that combines attaching to a thread and timers:
        # https://www.codeproject.com/Tips/76427/How-to-Bring-Window-to-Top-with-SetForegroundWindo

        return False