Search code examples
c#ms-wordcomexception

COMException unhandled in MS Word


We have a function which is supposed to get the range of the viewed text in a word document. However, we are getting the COMException in the first few lines of the function. The function is called with a fixed timer every 10 seconds.

We're dealing with this for quite some time and would appreciate any help/tips, Thank you.

private void GetViewedText()
    {
        // get the rectangle shown on the screen
        IntPtr h = System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle;

        h = FindWindowExW(h, new IntPtr(0), "_WwF", "");        
        h = FindWindowExW(h, new IntPtr(0), "_WwB", this.Application.ActiveDocument.Name);

        h = FindWindowExW(h, new IntPtr(0), "_WwG", "Microsoft Word Document");       

        RECT tagRect = new RECT();
        GetWindowRect(h, out tagRect);
        //-------------------------------------------------------------------------------------------------------

        //get the range in the doc from the rect
        // problem with "ActiveDocument" or "ActiveWindow"
        Word.Range r1 = (Word.Range)this.Application.ActiveWindow.RangeFromPoint(tagRect.left, tagRect.top); 

        Word.Range r2 = (Word.Range)this.Application.ActiveWindow.RangeFromPoint(tagRect.right, tagRect.bottom);

        Word.Range r = this.Application.ActiveDocument.Range(r1.Start, r2.Start);
        //-------------------------------------------------------------------------------------------------------

        //for each paragraph we increase the number of times read it and change the color
        for (int p = 1; p <= r.Paragraphs.Count; p++)
        {
            Word.Range rPar = document.Range(r.Paragraphs[p].Range);
            Word.Range rParNum = document.Range(rPar.Start, rPar.Start + 1);
            Word.Range rParText = document.Range(rPar.Start + 1, rPar.End);
            try
            {
                int parNum = Int32.Parse(rParNum.Text);
                paragraphs[parNum].ReadParagrafh();
                if (paragraphs[parNum].GetCounter() == 1)
                {
                    rParText.HighlightColorIndex = Word.WdColorIndex.wdYellow;
                }
                else if (paragraphs[parNum].GetCounter() == 2)
                {
                    rParText.HighlightColorIndex = Word.WdColorIndex.wdBrightGreen;
                }
                else
                {
                    rParText.HighlightColorIndex = Word.WdColorIndex.wdGreen;
                }
            }
            catch
            {
                continue;
            }
        }
    }

Solution

  • fixed it, had to remove the document.Range so the new line is:

    Word.Range rPar = r.Paragraphs[p].Range;