如何在扩展程序的代码编辑器中添加/删除代码?
例如:
我创建了一个扩展名女巫,修改了传入套接字中的代码
该示例使用Microsoft.VisualStudio.Text.Editor
尝试使用:IWpfTextView textView; // got from visual studio "Create" eventITextChange change; // Got from network socket or other source
ITextEdit edit = textView.TextBuffer.CreateEdit(); // Throws "Not Owner" Exceptionedit.Delete(change.OldSpan);edit.Insert(change.NewPosition, change.NewText);
但我想还有另一种方法,因为CrateEdit()函数失败
最佳答案
这里的问题是,您正在尝试从与拥有它的线程不同的线程上对ITextBuffer
进行编辑。这根本不可能。首次进行编辑后,ITextBuffer
实例将被附加到特定线程,此后将无法从其他线程对其进行编辑。在对TakeThreadOwnership
进行亲和之后,ITextBuffer
方法也将失败。可以从任何线程调用大多数其他非编辑方法(例如CurrentSnapshot
)。
通常,将ITextBuffer
关联到Visual Studio UI线程。因此,要执行编辑,请使用UI线程中的原始SynchronizationContext.Current
实例或Dispatcher.CurrentDispatcher
返回UI线程,然后执行编辑。
关于.net - 将代码添加到Visual Studio包/扩展中的当前编辑器窗口中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4326807/