Search code examples
pythoncomms-word

Using AccessibleObjectFromWindow in python on Microsoft Word instance


I am trying to manipulate a particular already-open, unsaved (so no path) Word document (*.doc) with python. The manipulations work great if only one Word instance is open, however multiple instances create some difficulty, reference the SO question Word VBA and Multiple Word Instances.

I have found some references on dealing with this in C# (How to access Microsoft Word existing instance using late binding) and VB.NET (Multiple Instances of Applications) and have managed to translate them to python to a point. Here's where I am now:

import win32com.client as win32
import win32gui
#GUID class from http://svn.python.org/projects/ctypes/tags/release_0_2/ctypes/comtypes/GUID.py
from GUID import GUID
from ctypes import oledll
from ctypes import byref
from comtypes import POINTER
from comtypes.automation import IDispatch

#Use win32 functions to get the handle of the accessible window
#of the desired Word instance.  Specific code not relevant here, 
#but I'll end up with an integer such as:
hwnd = 2492046

OBJID_NATIVEOM = 0xffffff0
IID_IDispatch = byref(GUID("{00020400-0000-0000-C000-000000000046}"))
p = POINTER(IDispatch)()
oledll.oleacc.AccessibleObjectFromWindow(hwnd, OBJID_NATIVEOM, IID_IDispatch, p)

When run, this returns the error message:

  File "wordtest.py", line 55, in <module>
    oledll.oleacc.AccessibleObjectFromWindow(hwnd, OBJID_NATIVEOM, IID_IDispatch, p)
  File "_ctypes/callproc.c", line 945, in GetResult
WindowsError: [Error -2147024809] The parameter is incorrect

Any assistance in fixing this error would be much appreciated!


Solution

  • Some searching through the GitHub code of NVDA (Non-Visual Desktop Access) showed that the value I was using for OBJID_NATIVEOM was incorrect, I needed to wrap the pointer in a byref(), and there was an easier way to get the GUID of IDispatch:

    #Part of the pywin32 package that must be installed with the pywin32
    #installer:
    import win32gui
    
    from ctypes import oledll
    from ctypes import byref
    
    #installed by easy_install comtypes
    from comtypes import POINTER
    from comtypes.automation import IDispatch
    import comtypes.client.dynamic as comDy
    
    #Handle integer hwnds[0] from code at 
    #http://stackoverflow.com/questions/33901597/getting-last-opened-ms-word-document-object
    
    OBJID_NATIVEOM = -16
    p = POINTER(IDispatch)()
    oledll.oleacc.AccessibleObjectFromWindow(hwnds[0], OBJID_NATIVEOM,
        byref(IDispatch._iid_), byref(p))
    
    window = comDy.Dispatch(p)
    word = window.application
    cert = word.Documents(1)