I do automated testing and get a file dialog. I want to choose a file from the windows open file dialog with python or selenium.
NOTE: The dialog is given by an other program. I don't want to create it with Tkinter.
The Window looks like:
.
How to do this?
Consider using the pywinauto package. It has a very natural syntax to automate any GUI programs.
Code example, opening a file in notepad. Note that the syntax is locale dependent (it uses the visible window titles / control labels in your GUI program):
from pywinauto import application
app = application.Application().start_('notepad.exe')
app.Notepad.MenuSelect('File->Open')
# app.[window title].[control name]...
app.Open.Edit.SetText('filename.txt')
app.Open.Open.Click()
You can use ctypes library.
Consider this code:
import ctypes
EnumWindows = ctypes.windll.user32.EnumWindows
EnumWindowsProc = ctypes.WINFUNCTYPE(ctypes.c_bool, ctypes.POINTER(ctypes.c_int), ctypes.POINTER(ctypes.c_int))
GetWindowText = ctypes.windll.user32.GetWindowTextW
GetWindowTextLength = ctypes.windll.user32.GetWindowTextLengthW
SendMessage = ctypes.windll.user32.SendMessageW
IsWindowVisible = ctypes.windll.user32.IsWindowVisible
def foreach_window(hwnd, lParam):
if IsWindowVisible(hwnd):
length = GetWindowTextLength(hwnd)
buff = ctypes.create_unicode_buffer(length + 1)
GetWindowText(hwnd, buff, length + 1)
if(buff.value == "Choose File to Upload"): #This is the window label
SendMessage(hwnd, 0x0100, 0x09, 0x00000001 )
return True
EnumWindows(EnumWindowsProc(foreach_window), 0)
You loop on every open window, and you send a key stroke to the one you choose.
The SendMessage function gets 4 params: the window hendler (hwnd
), The phisical key to send - WM_KEYDOWN (0x0100), The virtual-key code of tab
(0x09
) and the repeat count, scan code, extended-key flag, context code, previous key-state flag, and transition-state flag
in the 4th argument.
You can also send key up, key down, chars, returns and etc...
Use the documentation for help.
I used this as a reference: Win32 Python: Getting all window titles
Good luck!