How to minimize a specific window in Python

17,101

Well - the error in this code is that at the time you run win32gui.GetForegroundWindow(), there is no MS Word Window, and the current foreground window is probably the Python shell.

Try :

time.sleep(2)
Minimize = win32gui.GetForegroundWindow()
win32gui.ShowWindow(Minimize, win32con.SW_MINIMIZE)

I think it would be better if you used some other function to select the right window - not depending on timeout. Not sure, but FindWindow looks like what you need.

Share:
17,101
Anthony Alphabet
Author by

Anthony Alphabet

Updated on June 06, 2022

Comments

  • Anthony Alphabet
    Anthony Alphabet almost 2 years

    Hello I am new to Python and do not know how to minimize a specific window in this case Microsoft Word 2010 all I can minimize is the Python Shell. Here is my code just in case you need it.

    import win32gui, win32con
    import os
    import math
    import time
    
    M=6
    Minimize = win32gui.GetForegroundWindow()
    
    print("Program Started on "+time.ctime())
    
    while M >0:
    time.sleep(1)
    print(M," more seconds until Word is opened")
    M -=1
    
    time.sleep(1)    
    os.startfile("C:\Documents and Settings\All Users\Start Menu\Programs\MicrosoftOffice\Microsoft Word 2010")
    print("Microsoft Word 2010 opened "+time.ctime())
    
    time.sleep(2)
    win32gui.ShowWindow(Minimize, win32con.SW_MINIMIZE)