如何使用VSTO在Word中检测文本和光标位置的变化

时间:2020-03-05 18:51:12  来源:igfitidea点击:

我想编写一个单词addin来执行一些计算,并在用户键入任何内容或者移动当前插入点时更新一些ui。通过查看MSDN文档,我看不到任何明显的方式,例如文档或者应用程序对象上的TextTyped事件。

有谁知道在不轮询文档的情况下是否有可能?

解决方案

回答

正如我们可能已经发现的那样,Word有事件,但是它们是用于非常粗略的操作的,例如打开文档或者切换到另一个文档。我猜想MS故意这样做是为了防止糟糕的宏使输入速度变慢。

简而言之,没有什么好方法可以做我们想要的。 Word MVP在此线程中确认这一点。

回答

实际上,有一种方法可以在键入单词后运行一些代码,我们可以使用SmartTags并覆盖Recognize方法,只要键入单词,就会调用此方法,这意味着只要用户键入一些文本并敲空格,标签或者输入键。

但是,这样做的一个问题是,如果使用" Range.Text"更改文本,它将检测为单词更改并调用该函数,从而可能导致无限循环。

这是我用来实现此目的的一些代码:

public class AutoBrandSmartTag : SmartTag
{
    Microsoft.Office.Interop.Word.Document cDoc;

    Microsoft.Office.Tools.Word.Action act = new Microsoft.Office.Tools.Word.Action("Test Action");

    public AutoBrandSmartTag(AutoBrandEngine.AutoBrandEngine _engine, Microsoft.Office.Interop.Word.Document _doc)
        : base("AutoBrandTool.com/SmartTag#AutoBrandSmartTag", "AutoBrand SmartTag")
    {
        this.cDoc = _doc;

        this.Actions = new Microsoft.Office.Tools.Word.Action[] { act };
    }

    protected override void Recognize(string text, Microsoft.Office.Interop.SmartTag.ISmartTagRecognizerSite site, 
        Microsoft.Office.Interop.SmartTag.ISmartTagTokenList tokenList)
    {
        if (tokenList.Count < 1)
            return;

        int start = 0;
        int length = 0;
        int index = tokenList.Count > 1 ? tokenList.Count - 1 : 1;

        ISmartTagToken token = tokenList.get_Item(index);

        start = token.Start;
        length = token.Length;
    }
}