【问题标题】:How do you get the final Document.FullPath value AFTER closing a new WORD document?关闭新的 WORD 文档后如何获得最终的 Document.FullPath 值?
【发布时间】:2015-02-04 18:40:18
【问题描述】:

我有一个 Office WORD 加载项。我想知道如何确定文档关闭后的最终完整路径名。

具体来说,问题场景是这样的。用户创建一个新的 WORD 文档,对该文档进行编辑,然后关闭该文档。

在插件中,我检测到文档的创建。 DocumentBeforeClose 事件随后触发。然后 WORD 提示“是否要保存 Document1?”。选择是,DocumentBeforeSave 事件将触发。然后显示另存为对话框。用户提供完整路径并接受。 WORD 然后关闭。

我找不到捕获用户选择的对象模型方法或事件。

【问题讨论】:

    标签: c# ms-word vsto add-in


    【解决方案1】:

    ...4 周没有答案,所以我将针对我自己的问题提出一个答案...

    我还没有找到解决此问题的 Office 对象模型方法或属性。所以,我所做的是为 DocumentChange 事件注册一个处理程序。每当活动文档更改时,它就会触发。当活动文档变为无效时,它也会触发,就像文档关闭时一样。

    在处理程序中,我检测最后一个活动文档是否无效(通过捕获异常)。然后我查看注册表中的WORD MRU,找到最近使用的word文档。

    到目前为止,这种方法是有效且可靠的。但我觉得这是一种糟糕的方法。我欢迎更好更优雅的解决方案。这是我使用的代码...

    private void Application_DocumentChange()
    {
        // This event is fired every time the application sets a new active document, including
        // when the last active document is closed, in which case, Application.ActiveDocument
        // will be invalid.
    
        // Detect when a document has closed.
        // The previously active document is no longer active.  Check to see if the Doc object
        // is still valid.  If so, we can clear the IsClosing flag.  If not, we can assume it
        // was closed and queue it for post processing.
        if (_activeWrapper != null)
        {
            try
            {
                var lastDoc = _activeWrapper.Document();
                var path = lastDoc.FullName;
                _activeWrapper.IsClosing = false;  // set true in the close handler
            }
            catch (Exception ex)
            {
                if (_activeWrapper.IsClosing)
                {
                    // last document has closed
                    var path = RegistryTools.GetWordMRU(_appWrap.Version.ToString());
                    // do post-close processing on file
                }
                _activeWrapper.Dispose();
            }
        }
    
        Word.Document doc = null;
        DocWrapper wrapper = null;
        try
        {
            doc = Application.ActiveDocument; //will throw exception on last close
        }
        catch (Exception ex)
        {
            //if this exception is due to an invalid active document, then we can treat the
           //event as an indication that the last document has closed.
           return;  // WORD Closing
        }
    
        // remember the current active document
        if(doc != null)
            wrapper = DocWrapper.GetWrapper(doc);
        _activeWrapper = wrapper;
    }
    

    【讨论】:

      猜你喜欢
      • 2014-01-03
      • 1970-01-01
      • 2012-11-22
      • 1970-01-01
      • 2015-08-16
      • 2018-08-05
      • 1970-01-01
      • 1970-01-01
      • 2017-07-29
      相关资源
      最近更新 更多