获取活动的Word文档对象C#

时间:2019-01-21 11:36:35

标签: c# ms-word

我正在将VB6项目转换为C#,并且需要获取有效的Word文档对象。在vb6中,使用

很容易
func

我需要使用C#获取Word的活动Word文档。 我在项目中添加了以下引用

enter image description here

并将对类的引用添加为

dim objWordDoc as Word.Document
set objWordDoc = Word.ActiveDocument

是否有C#中的任何功能来获取活动的Word文档?

using Word = Microsoft.Office.Interop.Word;
using Office = Microsoft.Office.Core;

Private Word.Document _activeDocument;

请帮助我。

谢谢。

2 个答案:

答案 0 :(得分:0)

我找到了答案。

object word;
Word.Document _activeDocument;

        try
        {
            word = System.Runtime.InteropServices.Marshal.GetActiveObject("Word.Application");
            //If there is a running Word instance, it gets saved into the word variable
        }
        catch (Exception ex)
        {
            //If there is no running instance, it creates a new one
            Type type = Type.GetTypeFromProgID("Word.Application");
            word = System.Activator.CreateInstance(type);
        }


        Word.Application oWord = (Word.Application) word;
        _activeDocument = oWord.ActiveDocument

我已使用此问题的答案来找到答案。 Find existing instance of Office Application

答案 1 :(得分:0)

我认为

var app = Globals.ThisAddIn.Application;
var wind = app.ActiveWindow;
var doc = wind.Document;

Globals是外接程序类的成员。

相关问题