从当前文档中捕获文本

Capture text from current document

如何使用c#捕获您在word文档中编写的文本并将其保存到内存中。 对不起我的英语,谢谢你的回答

首先你必须从这里添加 Microsoft.Office.Interop.Word 到引用。

然后你可以将Word文档中的句子读成这样的字符串列表:

using Word = Microsoft.Office.Interop.Word;

public List<string> ReadWordDoc()
{
    object objMissing = System.Reflection.Missing.Value;            
    //Start Word application.
    Word._Application wordApp;
    Word._Document wordDoc;
    wordApp = new Word.Application();
    wordApp.Visible = false;

    object fileName = @"c:\temp\TestWord.docx";

    wordDoc = wordApp.Documents.Open(ref fileName,
        ref objMissing, ref objMissing, ref objMissing, ref objMissing, ref objMissing,
        ref objMissing, ref objMissing, ref objMissing, ref objMissing, ref objMissing,
        ref objMissing, ref objMissing, ref objMissing, ref objMissing, ref objMissing);

    List<string> sentences = new List<string>();    // List to store sentences.
    Word.Range rng;
    for (int i = 1; i < wordDoc.Sentences.Count+1; i++)
    {
        object startLocation = wordDoc.Sentences[i].Start;
        object endLocation = wordDoc.Sentences[i].End;

        // Supply a Start and End value for the Range. 
        rng = wordDoc.Range(ref startLocation, ref endLocation);

        // Select the Range.
        rng.Select();
        sentences.Add(rng.Text);
    }
    object doNotSaveChanges = Word.WdSaveOptions.wdDoNotSaveChanges;
    wordDoc.Close(ref doNotSaveChanges, ref objMissing, ref objMissing);
    wordApp.Quit(ref objMissing, ref objMissing, ref objMissing);

    return sentences;
}

@Batista:如果您要问如何监控用户在 Word 应用程序中的操作 - "capture the text you are writing" - 那么简短的回答是您不能。除了 WindowSelectionChange、WindowBeforeDoubleClick 和 WindowBeforeRightClick 等一些事件外,Word APIs 中没有任何东西支持监视击键和鼠标操作。

较长的答案是可以使用 Windows API 进行一些监控。如果您进行 Google 搜索,您应该会出现一些带有一些代码示例的讨论。我在 MSDN (https://social.msdn.microsoft.com/Forums/vstudio/en-US/home?forum=vsto) 的 VSTO 论坛中看到了这些。但是,您的情况可能会有所不同,因为 Windows API 在 Word 应用程序中截取消息的有效性因 Word 版本和 Windows.

版本而异。

谢谢 jhmt,您的解决方案很有帮助。但是句子之间的循环在最大的文档中会花费很多时间。

现在这是我的解决方案:

var objRange = Globals.ThisAddin.Application.ActiveDocument.Range();

然后用 objRange.Text 已经有了所有文本文件。