将代码添加到visual studio包/扩展中的当前编辑器窗口

时间:2010-12-01 16:53:31

标签: .net visual-studio vsix

如何在扩展程序中添加/删除代码编辑器中的代码?

例如:
我创建了一个扩展女巫修改来自插入的代码的代码 该示例使用Microsoft.VisualStudio.Text.Editor

尝试使用:

IWpfTextView textView; // got from visual studio "Create" event ITextChange change; // Got from network socket or other source

ITextEdit edit = textView.TextBuffer.CreateEdit(); // Throws "Not Owner" Exception edit.Delete(change.OldSpan); edit.Insert(change.NewPosition, change.NewText);

但我想还有另一种方法,因为CrateEdit()函数失败

2 个答案:

答案 0 :(得分:3)

这里的问题是您尝试从与拥有它的线程不同的线程对ITextBuffer进行编辑。这根本不可能。第一次编辑发生后,ITextBuffer个实例与特定线程相关联,在此之后,不能从不同的线程编辑它们。 TakeThreadOwnership关联ITextBuffer后,CurrentSnapshot方法也会失败。大多数其他非编辑方法(例如ITextBuffer)可以从任何线程调用。

通常,SynchronizationContext.Current将与Visual Studio UI线程关联。因此,要执行编辑,请使用UI线程中的原始Dispatcher.CurrentDispatcher实例或{{1}}来返回UI线程,然后执行编辑。

答案 1 :(得分:0)

这是我想出的代码

Dispatcher.Invoke(new Action(() =>
        {

            ITextEdit edit = _view.TextBuffer.CreateEdit();
            ITextSnapshot snapshot = edit.Snapshot;

            int position = snapshot.GetText().IndexOf("text:");
            edit.Delete(position, 5);
            edit.Insert(position, "some text");
            edit.Apply();
        }));