【问题标题】:Using AccessibleObjectFromWindow in python on Microsoft Word instance在 Microsoft Word 实例上的 python 中使用 AccessibleObjectFromWindow
【发布时间】:2016-03-04 15:59:52
【问题描述】:

我正在尝试使用 python 操作特定的已打开、未保存(因此没有路径)Word 文档 (*.doc)。如果只打开一个 Word 实例,则操作效果很好,但是多个实例会产生一些困难,请参考 SO 问题 Word VBA and Multiple Word Instances

我在 C# (How to access Microsoft Word existing instance using late binding) 和 VB.NET (Multiple Instances of Applications) 中找到了一些关于处理此问题的参考资料,并设法将它们翻译成 python。这是我现在的位置:

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)

运行时,返回错误信息:

  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

非常感谢您在修复此错误方面的任何帮助!

【问题讨论】:

    标签: python com ms-word


    【解决方案1】:

    通过 NVDA (Non-Visual Desktop Access) 的 GitHub 代码搜索显示我用于 OBJID_NATIVEOM 的值不正确,我需要将指针包装在 byref() 中,并且有一个更简单的方法来获取IDispatch 的 GUID:

    #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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-29
      • 2017-12-02
      • 1970-01-01
      • 2018-01-31
      • 1970-01-01
      相关资源
      最近更新 更多