Open file from windows file dialog with python automatically
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 applicationapp = 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 ctypesEnumWindows = ctypes.windll.user32.EnumWindowsEnumWindowsProc = ctypes.WINFUNCTYPE(ctypes.c_bool, ctypes.POINTER(ctypes.c_int), ctypes.POINTER(ctypes.c_int))GetWindowText = ctypes.windll.user32.GetWindowTextWGetWindowTextLength = ctypes.windll.user32.GetWindowTextLengthWSendMessage = ctypes.windll.user32.SendMessageWIsWindowVisible = ctypes.windll.user32.IsWindowVisibledef 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 TrueEnumWindows(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!