【问题标题】:Add code to current editor window in visual studio package/extention将代码添加到 Visual Studio 包/扩展中的当前编辑器窗口
【发布时间】:2010-12-01 16:53:31
【问题描述】:

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

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

尝试使用:

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

ITextEdit 编辑 = textView.TextBuffer.CreateEdit(); // 抛出“非所有者”异常 编辑.删除(更改.OldSpan); 编辑.插入(更改。新位置,更改。新文本);

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

【问题讨论】:

  • 你能发布完整的错误信息吗?
  • 错误:试图在错误的线程上编辑 TextBuffer。和“textView.TextBuffer.TakeThreadOwnership();” throws: 试图改变 TextBuffer 的编辑线程。

标签: .net visual-studio vsix


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    这是我发现的代码

    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();
            }));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-20
      • 2012-02-20
      • 1970-01-01
      • 1970-01-01
      • 2019-07-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多