2016-06-10 46 views
-1

selected.Contains会引发空指针异常,即使用户在调用方法之前选择了一些代码。我如何在Visual Studio 2015中获得用户选择的代码

this.package = package;   

string selected; 
selected = (string)this.ServiceProvider.GetService(typeof(TextSelection)); 

if (selected.Contains("for")) 
{ 
    MessageBox.Show("user " + "selected" + selected); 
} 
+0

selected =(string)this.ServiceProvider.GetService(typeof(TextSelection));是问题。该字符串为空,这就是为什么Contains方法不能被调用。 .GetService()返回什么,它实际上返回什么?由于它是空的。可能不是一个自然的转换 –

+0

在这一点上,我只想看到一个获取用户选择代码的工作示例。 GetService()返回一个方法。 @PetterPettersson – Christmas

+0

使用DTE.ActiveDocument.Selection http://stackoverflow.com/questions/24402325/how-to-add-text-in-active-document-using-c-sharp –

回答

1

我会给你最多的方式。

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

现在,你的脱口秀位置在你身上,弄清楚那里有什么。 类似于textView.GetTextElementSpan(caretPosition).GetText()

+0

谢谢。 @Paul Swetz – Christmas

+0

不要忘了标记它,如果你需要它。 –

相关问题