我们有一个函数可以获取word文档中查看文本的范围。但是,我们在函数的前几行中得到了COMException。每10秒钟使用一个固定的计时器调用该函数。
我们正在处理这个问题很长一段时间,并感谢任何帮助/提示,谢谢。
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;
}
}
}
答案 0 :(得分:0)
因为基于0的索引引用而崩溃吗?
for (int p = 1; p <= r.Paragraphs.Count; p++)
更改为
for (int p = 0; p < r.Paragraphs.Count; p++)
很多东西都是基于0的。假设你有4个段落。在文档内部,它们被引用为
paragraph[0], paragraph[1], paragraph[2], paragraph[3]
或
paragraph[1], paragraph[2], paragraph[3], paragraph[4]
段落的COUNT可能是4,但是引用为0-3 ...事情可能已经正常工作,例如:10段,并且它从1-9开始全部有效(因为10个条目将是0-9 ),但是当你尝试第10次时,没有这样的参考。
评论反馈......
从1开始,也许您应该尝试预先检查范围的NULL?
if( r.Paragraphs[p].Range == null )
continue;
Word.Range rPar = document.Range(r.Paragraphs[p].Range);
答案 1 :(得分:0)
修复它,不得不删除document.Range所以新行是:
Word.Range rPar = r.Paragraphs [p] .Range;