Click here to Skip to main content
15,867,986 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi,

I am using
using Microsoft.Office.Interop.Word;
assembly in order to access the word files and do some stuff. I want to know is there any way that I can get the character position where the cursor is currently in.

What I have tried:

Below is the code I use

Object wordObject = null;
           Microsoft.Office.Interop.Word.Application word = null;
           Document document = null;

           try {
               wordObject = (Microsoft.Office.Interop.Word.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Word.Application");

               word = (Microsoft.Office.Interop.Word.Application)wordObject;
               word.Visible = false;
               word.ScreenUpdating = false;
               string fullPath = word.ActiveDocument.FullName;

               document = word.Documents.Open(fullPath);

               int count = document.Words.Count;
               for(int k = 1; k <= count; k++)
               {
                   string text = document.Words[k].Text;
                   MessageBox.Show(text);
               }

               if (document.Paragraphs.Count > 0)
               {
                   var paragraph = document.Paragraphs.First;
                   var lastCharPos = paragraph.Range.Sentences.First.End - 1;
                   MessageBox.Show(lastCharPos.ToString());
               }
               word.Quit();
           }
           catch(Exception ex)
           {
               MessageBox.Show(ex.ToString());
           }


here I get the last character position of the first paragraph. But I want to get the character position where the cursor is located at the moment. Thanks in advanced!
Posted
Updated 21-Jul-20 21:16pm
Comments
Member 11380386 18-Nov-19 23:32pm    
Nobody is there to fix this problem?

How to get the cursor position in microsoft.interop.word?

Your app openened a SECOND copy of the "active document" ... there is no meaningful cursor info.
 
Share this answer
 
Comments
Dilan Shaminda 31-May-18 3:08am    
Could you please explain it more? How can I access the current active document?
Richard Deeming 31-May-18 13:10pm    
Replace:
document = word.Documents.Open(fullPath);

with:
document = word.ActiveDocument;


You'll probably also want to remove the call to word.Quit();, since you're attaching to an already-running instance of Word.
Hello you use this for get cursor position range
First must active document
C#
word_application.Selection.Range
 
Share this answer
 
Comments
Dave Kreskowiak 22-Jul-20 10:24am    
I seriously doubt the OP is still looking for a solution 2 years later.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900