首页 > 解决方案 > 使用 Python 在 Windows 文件打开对话框(由桌面应用程序启动)中指定文件

问题描述

像这样搜索许多 SO 帖子,我能够想出以下代码来访问 Windows 文件打开对话框。基本上我需要在这个对话框中指定一个由另一个应用程序打开的文件(没有使用 tKinter 的选项,而不是网络应用程序)。我收到如下错误

EnumChildWindows(currentHwnd,_windowEnumerationHandler,childWindows) ctypes.ArgumentError: argument 2: : 不知道如何转换参数 2

我在这里想念什么?有没有其他方法可以实现这个功能?

import ctypes
import win32gui

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
EnumChildWindows = ctypes.windll.user32.EnumChildWindows

WM_SETTEXT = 0x000C

def _windowEnumerationHandler(hwnd, resultList):
    #Pass to win32gui.EnumWindows() to generate list of window handle,
   # window text, window class tuples.
    resultList.append((hwnd, win32gui.GetClassName(hwnd)))

def searchChildWindows(currentHwnd,
                       wantedText=None,
                       wantedClass=None,
                       selectionFunction=None):
    childWindows = []
    result =[]
    EnumChildWindows(currentHwnd,_windowEnumerationHandler,childWindows)
    for childHwnd, windowText, windowClass in childWindows:
        descendentMatchingHwnds = searchChildWindows(childHwnd)
        if wantedClass == windowClass:
            result.append(childHwnd)

    return childHwnd

def getEditBox(hwnd):
    children = list(set(searchChildWindows(hwnd, 'ComboBoxEx32')))
    for addr_child in children:
        if (win32gui.GetClassName(addr_child) == 'Edit'):
            print(f"found TextBox")
            SendMessage(hwnd, WM_SETTEXT, 0, "Can I change this title?")

def foreach_window_child(hwnd, lParam):
    if IsWindowVisible(hwnd):
        length = GetWindowTextLength(hwnd)
        buff = ctypes.create_unicode_buffer(length + 1)
        GetWindowText(hwnd, buff, length + 1)
        if (buff.value == "Open"):  # This is the window label
            print(f"foreach_window_child found it")
            #SendMessage(hwnd, WM_SETTEXT, 0, "Do u see me ") # Changes the title of dlg box
            getEditBox(hwnd)
    return True

EnumWindows(EnumWindowsProc(foreach_window_child), 0)

标签: pythonwin32gui

解决方案


愚蠢的错误

EnumChildWindows(currentHwnd,_windowEnumerationHandler,childWindows)

 EnumChildWindows(currentHwnd[0],_windowEnumerationHandler,childWindows)

解决了问题


推荐阅读