2010-12-01 61 views
3

如何在代码编辑器中从扩展中添加/删除代码?将代码添加到Visual Studio包中的当前编辑器窗口/延伸

例如:
我创建的扩展女巫从进入的插座
该示例使用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()函数失败

+0

您可以发布完整的错误消息? – JaredPar 2010-12-01 16:59:55

+0

错误:试图在错误的线程上编辑TextBuffer。 和“textView.TextBuffer.TakeThreadOwnership();”引发: 试图更改TextBuffer的编辑线程。 – 2010-12-01 17:35:03

回答

3

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

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

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(); 
     })); 
相关问题