Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need to bring a windows application(Excel in my case) to foreground - python

I am creating a windows automation script. I need to bring Excel application to foreground. I am able to open excel application and get list of subprocess running. But i am not sure how to Excel application to foreground. Please help

import subprocess
from win32com.client import Dispatch

xl = Dispatch("Excel.Application")
xl.Visible = True 

cmd = 'WMIC PROCESS get Caption,Commandline,Processid'
proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
for line in proc.stdout:
    print(line)

I am getting list of applications open, but i need to bring Excel to foreground. Please help me how to do it.

b'EXCEL.EXE "C:\Program Files\Microsoft Office\root\Office16\EXCEL.EXE"
b'SearchFilterHost.exe 740 \r\r\n' b'python.exe C:\Users\arvin\AppData\Local\Programs\Python\Python37-32\python.exe \r\r\n' b'conhost.exe \??\C:\WINDOWS\system32\conhost.exe 0x4 15724 \r\r\n' b'cmd.exe C:\WINDOWS\system32\cmd.exe /c "WMIC PROCESS get Caption,Commandline,Processid" 18084 \r\r\n'

like image 637
Arvinth Avatar asked Oct 15 '25 05:10

Arvinth


2 Answers

If you are using all Microsoft Office applications, chances are object.Activate() method will work. This is part of Microsoft VBA and C# application calls that are also available to 3rd party languages. Code below was tested on my Windows 10 environment, python 3.7 with pywin32, and MS-Office 2013.

####### Activate one excel file ##############
import win32com.client as win32
excel = win32.gencache.EnsureDispatch('Excel.Application')
wb1 = excel.Workbooks.Open(r'C:\python\so\sheet1.xlsx')
wb2 = excel.Workbooks.Open(r'C:\python\so\sheet2.xlsx')
wb3 = excel.Workbooks.Open(r'C:\python\so\sheet3.xlsx')    
excel.Visible = True

# This will open 3 workbooks with wb1 on top.

excel.Application.ActiveWorkbook.Name
# Prints name of currently active workbook, i.e., the one on top.

wb3.Activate()  # puts workbook3 on top
wb2.Activate()  # puts workbook2 on top

### You may need to install pywin32.
### pip install pywin32
like image 179
Jennifer Yoon Avatar answered Oct 17 '25 17:10

Jennifer Yoon


If you really need to bring the excel window to foreground you can do this:

from win32com.client import Dispatch
from win32gui import SetForegroundWindow

xl = Dispatch("Excel.Application")
xl.Visible = True
SetForegroundWindow(xl.hwnd)

Where hwnd is the excel's window id. More information about hwnd

like image 23
Carlos Porta Avatar answered Oct 17 '25 17:10

Carlos Porta