C# 如何在Visual Studio 2015中获取用户选择的代码
C# 如何在Visual Studio 2015中获取用户选择的代码,c#,visual-studio-2015,selectedtext,C#,Visual Studio 2015,Selectedtext,selected.Contains抛出空指针异常,即使用户在调用该方法之前选择了一些代码 this.package = package; string selected; selected = (string)this.ServiceProvider.GetService(typeof(TextSelection)); if (selected.Contains("for")) { MessageBox.Show("user " + "selected" + se
selected.Contains
抛出空指针异常,即使用户在调用该方法之前选择了一些代码
this.package = package;
string selected;
selected = (string)this.ServiceProvider.GetService(typeof(TextSelection));
if (selected.Contains("for"))
{
MessageBox.Show("user " + "selected" + selected);
}
我会带你去那里的
private IVsEditorAdaptersFactoryService GetEditorAdaptersFactoryService()
{
IComponentModel componentModel =(IComponentModel)GetService(typeof(SComponentModel));
return componentModel.GetService<IVsEditorAdaptersFactoryService>();
}
private Microsoft.VisualStudio.Text.Editor.IWpfTextView GetTextView()
{
IVsTextManager textManager = (IVsTextManager)GetService(typeof(SVsTextManager));
if (textManager == null)
return null;
IVsTextView textView = null;
textManager.GetActiveView(1, null, out textView);
if (textView == null)
return null;
return GetEditorAdaptersFactoryService().GetWpfTextView(textView);
}
public void SomeFUnction()
{
Microsoft.VisualStudio.Text.Editor.IWpfTextView textView = GetTextView();
if (textView != null)
{
SnapshotPoint caretPosition = textView.Caret.Position.BufferPosition;
}
}
private IVSEditor AdapterFactoryService GetEditorAdapterFactoryService()
{
IComponentModel componentModel=(IComponentModel)GetService(typeof(SComponentModel));
返回componentModel.GetService();
}
私有Microsoft.VisualStudio.Text.Editor.IWpfTextView GetTextView()
{
IVsTextManager textManager=(IVsTextManager)GetService(typeof(SVsTextManager));
if(textManager==null)
返回null;
IVsTextView textView=null;
GetActiveView(1,null,out textView);
if(textView==null)
返回null;
返回GetEditorAdaptersFactoryService().GetWpfTextView(textView);
}
公共函数()
{
Microsoft.VisualStudio.Text.Editor.IWPTextView textView=GetTextView();
if(textView!=null)
{
SnapshotPoint caretPosition=textView.Caret.Position.BufferPosition;
}
}
现在,你有了插入符号的位置,它在你身上,以找出有什么。
类似于textView.GetTextElementSpan(caretPosition).GetText()selected=(字符串)this.ServiceProvider.GetService(typeof(TextSelection));这就是问题所在。字符串为null,这就是无法调用Contains方法的原因。.GetService()返回什么?它实际返回什么?因为它是空的。这可能不是一个自然的转换。在这一点上,我只想看到一个让用户选择代码的工作示例。GetService()正在返回一个方法@PettersUse DTE.ActiveDocument.Selection