python操作word 调用vb_在Microsoft Word实例上的python中使用AccessibleObjectFromWindow

1586010002-jmsa.png

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

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!

解决方案

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)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值