Windows dialog box removal

Dave Brueck dave at pythonapocrypha.com
Wed Sep 24 09:47:53 EDT 2003


On Thursday 25 September 2003 06:18 am, SectorUnknown wrote:
> I've written a Python script that runs a MS Windows program using popen.
> However, at the end of the Windows program, a dialog box appears and
> asks for the user to click on OK.
>
> Is there a way to have Python set focus on the dialog box and click OK
> so my script can continue?
>
> Does anyone have an example?

I wouldn't be surprised if there's an easier or more correct way to do this, 
but if you can reliably know the title of the window then the code below 
should work (assuming you have ctypes installed):

from ctypes import *
user32 = windll.user32

EnumWindowsProc = WINFUNCTYPE(c_int, c_int, c_int)

def GetHandles(title, parent=None):
    'Returns handles to windows with matching titles'
    hwnds = []
    def EnumCB(hwnd, lparam, match=title.lower(), hwnds=hwnds):
        title = c_buffer(' ' * 256)
        user32.GetWindowTextA(hwnd, title, 255)
        if title.value.lower() == match:
            hwnds.append(hwnd)

    if parent is not None:
        user32.EnumChildWindows(parent, EnumWindowsProc(EnumCB), 0)
    else:
        user32.EnumWindows(EnumWindowsProc(EnumCB), 0)
    return hwnds

Here's an example of calling it to click the Ok button on any window that has 
the title "Downloads properties" (most likely there are 0 or 1 such windows):

for handle in GetHandles('Downloads properties'):
    for childHandle in GetHandles('ok', handle):
        user32.SendMessageA(childHandle, 0x00F5, 0, 0) # 0x00F5 = BM_CLICK

-Dave





More information about the Python-list mailing list