我正在使用 MEF 开发 Visual Studio 2013 扩展,同时尝试读取 Active Document 内容类型和代码。目前,它仅在编辑器中打开文档/项目项时读取。一旦打开它们,每当我们在打开的文档选项卡之间切换时,它就不会再次读取它们。
要求:我希望此扩展能够读取当前活动文档的内容类型和代码文本。
Updated:
Problem:我知道,使用 EnvDTE80.DTE2.ActiveWindow,我可以获取当前聚焦的文档,但我很困惑如何调用此代码来读取当前活动文档/窗口的内容?假设我们有 10 个文档,则活动文档(获得当前焦点)需要由 this 扩展读取。这里,只有当我们打开一个新文档或创建文本视图之前关闭的文档时,才会调用 VsTextViewCreated 。它不会被调用已经打开的文档(即已经创建的文本视图),因此我们在将焦点移到其他已经打开的文档上时将无法获得更新的 wpfTextView 对象。我很困惑如何使用 DTE2.ActiveDocument 或 DTE2.ActiveWindow 事件处理程序来调用它。
问题:
这在 MEF 中是否可行,而不使用 DTE?
VS 编辑器中是否存在处理 TextView 的接口?
这是我的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.VisualStudio.Text.Tagging;
using Microsoft.VisualStudio.Text.Editor;
using System.ComponentModel.Composition;
using Microsoft.VisualStudio.Utilities;
using Microsoft.VisualStudio.Editor;
using Microsoft.VisualStudio.TextManager.Interop;
using Microsoft.VisualStudio.OLE.Interop;
using System.Diagnostics;
namespace VSIXProject_Test
{
[Export(typeof(IVsTextViewCreationListener))]
[ContentType("code")]
[TextViewRole(PredefinedTextViewRoles.Editable)]
class VsTextViewCreationListener : IVsTextViewCreationListener
{
[Import]
IVsEditorAdaptersFactoryService AdaptersFactory = null;
public void VsTextViewCreated(IVsTextView textViewAdapter)
{
var wpfTextView = AdaptersFactory.GetWpfTextView(textViewAdapter);
if (wpfTextView == null)
{
Debug.Fail("Unable to get IWpfTextView from text view adapter");
return;
}
Debug.Write(wpfTextView.TextBuffer.ContentType.TypeName);
}
}
}
幸运的是,我得到了我想要达到的目标。辅助解决方案已经发布here:
我在 dte2.Events.WindowsEvents.WindowActived 中使用了辅助方法并获取 IVsTextView 对象来检索文本缓冲区。这是我的 WindowActivated 事件的代码片段:
void WindowEvents_WindowActivated(EnvDTE.Window GotFocus, EnvDTE.Window LostFocus)
{
if (null != GotFocus.Document)
{
Document curDoc = GotFocus.Document;
Debug.Write("Activated : " + curDoc.FullName);
this.IvsTextView=GetIVsTextView(curDoc.FullName); //Calling the helper method to retrieve IVsTextView object.
if (IvsTextView != null)
{
IvsTextView.GetBuffer(out curDocTextLines); //Getting Current Text Lines
//Getting Buffer Adapter to get ITextBuffer which holds the current Snapshots as wel..
Microsoft.VisualStudio.Text.ITextBuffer curDocTextBuffer = AdaptersFactory.GetDocumentBuffer(curDocTextLines as IVsTextBuffer);
Debug.Write("\r\nContentType: "+curDocTextBuffer.ContentType.TypeName+"\nTest: " + curDocTextBuffer.CurrentSnapshot.GetText());
}
}
}
现在,这适用于在 VS 编辑器中打开的所有代码文档。希望这能帮助像我这样的人。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)