Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to minimize a specific window in Python

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)
like image 569
Anthony Alphabet Avatar asked May 17 '26 07:05

Anthony Alphabet


1 Answers

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.

like image 95
fitek Avatar answered May 18 '26 20:05

fitek