c#ms word获得可见文本

Nac*_*cho 6 c# office-interop

我正在尝试使用Microsoft.Office.Interop.Word获取C#中MS Word窗口中显示的文本.请注意,这不是整个文件甚至是页面; 只是用户看到的相同内容.

以下代码似乎适用于简单文档:

Application word = new Application();
word.Visible = true;
object fileName = @"example.docx";
word.Documents.Add(ref fileName, Type.Missing, Type.Missing, true);

Rect rect = AutomationElement.FocusedElement.Current.BoundingRectangle;

Range r1 = word.ActiveWindow.RangeFromPoint((int)rect.Left, (int)rect.Top);
Range r2 = word.ActiveWindow.RangeFromPoint((int)rect.Left + (int)rect.Width, (int)rect.Top + (int)rect.Height);
r1.End = r2.Start;

Console.WriteLine(r1.Text.Replace("\r", "\r\n"));
Run Code Online (Sandbox Code Playgroud)

但是,当文档包含其他结构(如标题)时,只返回部分文本.

那么,实现这一目标的正确方法是什么?

非常感谢!

更新的代码

Rect rect = AutomationElement.FocusedElement.Current.BoundingRectangle;

foreach (Range r in word.ActiveDocument.StoryRanges) {
    int left = 0, top = 0, width = 0, height = 0;
    try {
        try {
            word.ActiveWindow.GetPoint(out left, out top, out width, out height, r);
        } catch {
            left = (int)rect.Left;
            top = (int)rect.Top;
            width = (int)rect.Width;
            height = (int)rect.Height;
        }
        Rect newRect = new Rect(left, top, width, height);
        Rect inter;
        if ((inter = Rect.Intersect(rect, newRect)) != Rect.Empty) {
            Range r1 = word.ActiveWindow.RangeFromPoint((int)inter.Left, (int)inter.Top);
            Range r2 = word.ActiveWindow.RangeFromPoint((int)inter.Right, (int)inter.Bottom);
            r.SetRange(r1.Start, r2.Start);

            Console.WriteLine(r.Text.Replace("\r", "\r\n"));
        }
    } catch { }
}
Run Code Online (Sandbox Code Playgroud)

Joh*_*Zaj 4

这可能存在一些问题:

  • 它不可靠。你真的每次都能得到一致的结果吗?例如,在一个简单的“=rand()”文档上,连续运行程序5次而不改变Word的状态。当我这样做时,每次我都会在控制台上打印不同的范围。我首先从这里开始:您获取范围的逻辑似乎有问题。例如,每次我对屏幕上留下的同一个文档执行 rect.Left 时,它都会返回不同的数字
  • 其他故事就变得很棘手。也许 RangeFromPoint 无法
    跨越多个故事边界。然而,我们假设确实如此。您仍然需要枚举每个故事,例如

enumerator = r1.StoryRanges.GetEnumerator(); { while (enumerator.MoveNext() { Range current = (Range) enumerator.Current; } }

您是否尝试过查看如何以编程方式提取 Office.Interop.Word.Document 对象当前查看页面的文本?