【问题标题】:VSTO Document-level customisation ThreadingVSTO 文档级自定义线程
【发布时间】:2017-03-09 00:01:37
【问题描述】:

我们正在为 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)).

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

谢谢

【问题讨论】:

    标签: c# multithreading ms-word vsto


    【解决方案1】:

    首先,您不应该从后台线程访问 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

    【讨论】:

    • 谢谢,这帮助很大。对于其他人来说,似乎 CustomDocumentProperties 在从不同的线程访问时返回一个动态,因此会出现强制转换异常
    • 在这个答案的最后一个链接dynamic 中有一个不那么冗长的解决方案。据我所知,它们在功能上是等效的,并且代码是这个答案只在 C# 4.0 之前相关。还有@Eugene,我认为您的第一句话缺少“不”。
    • 对,第一句漏掉了一个'not'部分。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多