我正在尝试使用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
非常感谢任何修复此错误的帮助!
答案 0 :(得分:0)
通过NVDA(非可视桌面访问)的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)