Search code examples
pythonpywinauto

Pywinauto: How to set focus window on a program - Excel


I am new to Python and recently we need to automate the measurement reading from the meter. Hence, we use Pywinauto to automate the tasks.

We need to copy and paste the measurement values from meter custom software to Excel program itself and I written something like this.

from pywinauto import Application
from pywinauto import findwindows
from pywinauto.keyboard import send_keys


#Block of code that read data from the meter

#Starting the app
app = Application(backend="uia")
#app.start(r"C:/Program Files/Microsoft Office/root/Office16/EXCEL.exe")
app.connect(path=r"C:/Program Files/Microsoft Office/root/Office16/EXCEL.exe")


#Start - Block of Codes to focus on Excel programs
#???
#End - Block of Codes to focus on Excel programs

#Pseudocode of getting data from the meter
c = "9.8651"
send_keys(c) # to type PYWINAUTO
send_keys("{VK_RIGHT}") #Offset to right

How can I set that Pywinauto will "set focus" on Excel program itself once it copy the data from the custom software ? Thank you.


Solution

  • Edit: Vasily provided a more elegant solutions. Changed the answer according to his recommendations.

    I already have an answer for the solutions above:

    Use win = app.window(title_re='.*Excel')and type_keys as per mentioned by Vasily in the comments.

    from pywinauto import Application
    from pywinauto import findwindows
    
    
    
    #Block of code that read data from the meter
    
    #Starting the app
    app = Application(backend="uia")
    #app.start(r"C:/Program Files/Microsoft Office/root/Office16/EXCEL.exe")
    app.connect(path=r"C:/Program Files/Microsoft Office/root/Office16/EXCEL.exe")
    
    
    #Start - Block of Codes to focus on Excel programs
    win = app.window(title_re='.*Excel')
    #End - Block of Codes to focus on Excel programs
    
    #Pseudocode of getting data from the meter
    c = "9.8651"
    win.type_keys(c)
    win.type_keys("{VK_RIGHT}")