Python Window Activation

Python Window Activation

You can use the win32gui module to do that. First you need to get a valid handle on your window. You can use the win32gui.FindWindow if you know the window class name or the exact title. If not, you can enumerate the windows with the win32gui.EnumWindows and try to find the right one.

Once you have the handle, you can call the win32gui.SetForegroundWindow with the handle. It will activate the window and will be ready for getting your keystrokes.

See an example below. I hope it helps

import win32gui
import re

class WindowMgr:
"""Encapsulates some calls to the winapi for window management"""

def __init__ (self):
"""Constructor"""
self._handle = None

def find_window(self, class_name, window_name=None):
"""find a window by its class_name"""
self._handle = win32gui.FindWindow(class_name, window_name)

def _window_enum_callback(self, hwnd, wildcard):
"""Pass to win32gui.EnumWindows() to check all the opened windows"""
if re.match(wildcard, str(win32gui.GetWindowText(hwnd))) is not None:
self._handle = hwnd

def find_window_wildcard(self, wildcard):
"""find a window whose title matches the wildcard regex"""
self._handle = None
win32gui.EnumWindows(self._window_enum_callback, wildcard)

def set_foreground(self):
"""put the window in the foreground"""
win32gui.SetForegroundWindow(self._handle)

w = WindowMgr()
w.find_window_wildcard(".*Hello.*")
w.set_foreground()

Change the active Window

I think the object method you're after is activate:

>>> help(win.activate)
Help on method activate in module
pygetwindow._pygetwindow_win:

activate() method of
pygetwindow._pygetwindow_win.Win32Window instance
Activate this window and make it the foreground window.

So changing your code as follows should work.

import pygetwindow as gw

win = gw.getWindowsWithTitle('Photoshop')[0]
win.activate()

Python activate windows with the same name

To cycle through selected windows, there's a few steps:

  • Use win32gui.EnumWindows to go through all open windows
  • Use win32gui.GetWindowText to get the title bar text from a window
  • Use win32com.client.Dispatch and SendKeys to activate the switch process
  • Use win32gui.SetForegroundWindow to select the window to activate

Here's the code:

import win32com.client as win32
import win32gui
import time

title = "Untitled - Notepad2" # cycle all windows with this title

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

top_windows = [] # all open windows
win32gui.EnumWindows(windowEnumerationHandler, top_windows)

winlst = [] # windows to cycle through
for i in top_windows: # all open windows
if i[1] == title:
winlst.append(i)

for x in range(5): # cycle 5 times
for w in winlst: # each window with selected title
shell = win32.Dispatch("WScript.Shell") # set focus on desktop
shell.SendKeys('%') # Alt key
win32gui.SetForegroundWindow(w[0]) # bring to front, activate
time.sleep(2) # 2 seconds

Issue with virtualenv - cannot activate

source is a shell command designed for users running on Linux (or any Posix, but whatever, not Windows).

On Windows, virtualenv creates a .bat/.ps1 file, so you should run venv\Scripts\activate instead (per the virtualenv documentation on the activate script).

Just run activate, without an extension, so the right file will get used regardless of whether you're using cmd.exe or PowerShell.

virtualenv' won't activate on Windows

According to Microsoft Tech Support it might be a problem with Execution Policy Settings. To fix it, you should try executing Set-ExecutionPolicy Unrestricted -Scope Process (as mentioned in the comment section by @wtsiamruk) in your PowerShell window. This would allow running virtualenv in the current PowerShell session.

There is also another approach that is more unsafe, but recommended by MS Tech Support. This approach would be to use Set-ExecutionPolicy Unrestricted -Force (which do unleash powers to screw Your system up). However, before you use this unsafe way, be sure to check what your current ExecutionPolicy setting is by using get-ExecutionPolicy. Then, when you are done, you can revert back to this ExecutionPolicy by using Set-ExecutionPolicy %the value the get-ExecutionPolicy command gave you% -Force.

How do I activate my virtual environment in Windows?

Use the following:

.\ll_env\Scripts\activate

How to activate an environment using PowerShell from any directory in one single command?

Running something like this from PowerShell:

C:\Users\Admin\Desktop\pyenv\Scripts\activate.bat

It works, but doesn't have the effect you expect. Running a batch file from PowerShell will launch a new instance of cmd, which will get the activated environment - but once the batch file completes, the cmd process is done and will be terminated, taking the modified environment variables with it.

You could write a batch file like this and it would work (from both Command Prompt and PowerShell) as expected:

call C:\Users\Admin\Desktop\pyenv\Scripts\activate.bat
python myscript.py

It would run myscript.py in the intended environment.

Running just the batch file activation command (with path) from a running Command Prompt works in a way that you probably expected to work in PowerShell as well. It modifies the current environment and allows you to interactively run commands in it afterwards, until you deactivate.

However, if you want to change the current environment on the current PowerShell prompt, you need to run (this is the answer):

C:\Users\Admin\Desktop\pyenv\Scripts\activate.ps1

i.e. run the .ps1 PowerShell script, don't run the .bat Command Prompt script.

Note: something that may cause this confusion is that Windows Commmand Prompt automatically runs script.bat if the script command is entered (and there are no other script.___ files that have an extension that comes before .bat in the PATHEXT variable); however, PowerShell finds the script (no extension) file and settles for that. You can see that this is the case by running:

Get-Command C:\Users\Admin\Desktop\pyenv\Scripts\activate

PowerShell does also use PATHEXT, but matches the filename without extension before it and that file is there (it's the Bash script):

Write-Host $env:PATHEXT

(more on PowerShell's use of environment variables here)

virtualenv not activated on windows 11

According to Microsoft Tech Support, it might be a problem with Execution Policy Settings. To fix it, you should try executing the Set-ExecutionPolicy Unrestricted -Scope Process

OR IF this problem is not gone Then please read this answer

To activate

.\Scripts\activate

or

.\Scripts\activate.bat

FOR deactivating venv

.\onlineShop\Scripts\deactivate.bat

or

.\onlineShop\Scripts\deactivate

or

deactivate 

If you got any error while activating the virtual Environment:

cannot be loaded because
running scripts is disabled on this system. For more information, see about_Execution_Policies at
https:/go.microsoft.com/fwlink/?LinkID=135170.

This means your Execution Policy is Restricted SO. To get rid of this error you can run this command.

In Command Prompt:

powershell Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy Unrestricted

In Powershell:

Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy Unrestricted

Make auto key and mouse press on activate window on Python

This will help you to automate:

for mouse clicks:

import pyautogui
pyautogui.click(1319, 45)
pyautogui.scroll(200)
pyautogui.hotkey("ctrlleft", "a")

For keyboard

import keyboard
# It writes the keys r, k and endofline
keyboard.press_and_release('shift + r, shift + k, \n')
keyboard.press_and_release('R, K')
# it blocks until esc is pressed
keyboard.wait('esc')

# It records all the keys until escape is pressed
rk = keyboard.record(until='Esc')

# It replay back the all keys
keyboard.play(rk, speed_factor=1)


Related Topics



Leave a reply



Submit