I am working on an automation project which requires me to search for an acrobat process and then bring it to foreground. I am using Windows Server 2012 R2 Standard and Python. I search for that specific PDF file in the process list and then I try to bring that window to foreground.
My code runs fine when the server is open and active. As soon as it gets minimized or locked, it doesn't work. Specifically, the line SetForegroundWindow() does not work and throws an error "(0, 'SetForegroundWindow', 'No error message is available')".
Next, I went through many examples listed here and someone suggested to use 'Alt' tab before that line. Tried, didn't work. Then I used ShowWindow() according to an another user but then again the same error is coming. Now, I am totally stuck.
I have already viewed many threads related to the problem such as: 1. SetForegroundWindow doesn't work with minimized process 2. Bring to forward window when minimized 3. Bring to forward window when minimized
I tried MainWindowHandle could fix the error but I am not able to implement it in python.
Also, I installed pywinauto and used findwindows and SetForegroundWindow function of pywinauto. It works well when server is active but as soon as we minimze or lock the server, it doesn't work and gives the same error "(0, 'SetForegroundWindow', 'No error message is available')".
Now, I am totally out of options. Any ideas/suggestions?
Here is the snippet:
import win32gui,win32con
import win32com.client
import time
time.sleep(3)
def windowEnumerationHandler(hwnd, top_windows):
if win32gui.IsWindowVisible(hwnd) and win32gui.GetWindowText(hwnd)!='':
top_windows.append((hwnd, win32gui.GetWindowText(hwnd)))
results = []
top_windows = []
file_name_of_pdf = "ARW_AR_2016.pdf"
win32gui.EnumWindows(windowEnumerationHandler, top_windows)
for i in top_windows:
if i[1].find(file_name_of_pdf[:len(file_name_of_pdf)-4])>-1:
print(i)
shell = win32com.client.Dispatch("WScript.Shell")
win32gui.ShowWindow(i[0],9)
try:
shell.SendKeys('%')
win32gui.ShowWindow(i[0], win32con.SW_RESTORE)
win32gui.SetForegroundWindow(i[0])
except Exception as e:
print(1,e)
try:
shell.SendKeys('%')
win32gui.SetForegroundWindow(i[0])
except Exception as r:
print(2,r)
pass