I want to switch the current window with python. I saw a post that should answer my question in Python Window Activation, but it didn't. First I made a class to put the function in:
class WindorMgr:
def change_window(self, name, in_window_name=False):
from win32gui import EnumWindows, SetForegroundWindow, GetWindowText
from re import match
handle = None
def find_window(num, name):
if not in_window_name:
if match(name, str(GetWindowText(num))) is not None:
SetForegroundWindow(num)
else:
name = name.lower()
try:
handle = str(GetWindowText(num)).lower()
handle.index(name)
SetForegroundWindow(num)
except:
pass
EnumWindows(find_window, name)
I don't know if it's okay to put a methond in another method, but it worked, so I made like that. When I run the script it actually works, but it only changes the window once.
I made the test like that:
if __name__ == '__main__':
from time import sleep
windowmgr = WindowMgr()
windowmgr.change_window('opera', in_window_name=True)
sleep(5)
windowmgr.change_window('Word')
As I said, it changes the window once. When the script starts running, it changes the window to Opera browser, but after the 4 seconds it doesn't change to Microsoft Word. Instead the Microsoft Word icon turns yellow. What should I do to make it work as I want it to?