VSTO 文档级自定义线程

VSTO Document-level customisation Threading

我们正在为 MS word 开发 VSTO 文档级自定义。我们需要从后台线程访问文档,这样我们就不会停止 UI 刷新。

这适用于 DocumentBase 上的 Sections / Table 等属性。

尝试访问 CustomDocumentProperties 或 BuiltInDocumentProperties 时收到以下异常

Unable to cast COM object of type 'System.__ComObject' to interface type 'Microsoft.Office.Core.DocumentProperties'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{2DF8D04D-5BFA-101B-BDE5-00AA0044DE52}' failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE)).

是否可以从后台线程访问这些属性?

谢谢

首先,您不应该从后台线程访问 Office 对象模型,因为 Office 应用程序使用单线程单元模型。

使用后期绑定技术访问文档属性,请参阅Type.InvokeMember方法了解更多信息。例如:

object properties = workBk.GetType().InvokeMember("CustomDocumentProperties", BindingFlags.Default | BindingFlags.GetProperty, null, workBk, null);

object property = properties.GetType().InvokeMember("Item", BindingFlags.Default | BindingFlags.GetProperty, null, properties, new object[] { propertyIndex });

object propertyValue = property.GetType().InvokeMember("Value", BindingFlags.Default | BindingFlags.GetProperty, null, propertyWrapper.Object, null);

你也可以看看类似的页面:

Set custom document properties with Word interop

Accessing Excel Custom Document Properties programatically