0

I am converting a VB6 project to C# and I need to get the Active word document object. In vb6 it is easy by using

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

I need to get the Word's active word document using C#. I have added the below references to the project

enter image description here

And added the references to the class as

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

Private Word.Document _activeDocument;

Is there any function like in C# to get the active word document?

_activeDocument = Word.Application.ActiveDocument;
Dharman
  • 30,962
  • 25
  • 85
  • 135
ApsSanj
  • 549
  • 7
  • 23
  • Did you check - https://learn.microsoft.com/en-us/dotnet/api/microsoft.office.interop.word?view=word-pia? – Incredible Jan 21 '19 at 11:55
  • 1
    which interop method are you using? PIA? usually when interfacing Office from C#, you would create a new instance of the application object, open or create a new document, and continue working with this reference as your "activedocument". – Cee McSharpface Jan 21 '19 at 11:56
  • Show us the code to start up (or "get") the Word application. The last code snippet you show should work, but it's first necessary to "start" or "get" the Word.Application - same as in VB6. – Cindy Meister Jan 21 '19 at 12:13

2 Answers2

0

I have found the answer.

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

I have used the answer in this question to find this. Find existing instance of Office Application

ApsSanj
  • 549
  • 7
  • 23
0

I think

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

A Globals is the member of the add-in class.