-1

The selected.Contains throws a null pointer exception, even though the user has selected some code before invoking the method.

this.package = package;        

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

if (selected.Contains("for")) 
{
    MessageBox.Show("user "  + "selected" + selected);
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Christmas
  • 3
  • 1
  • selected = (string)this.ServiceProvider.GetService(typeof(TextSelection)); is the problem. The string is null and thats why Contains method can't be called. What does .GetService() return and does it actually return anything? Since it's null. Might not be a natural conversion – Petter Pettersson Jun 10 '16 at 09:48
  • At this point I just want to see a working example of getting user selected code. GetService() was returning a method. @PetterPettersson – Christmas Jun 10 '16 at 11:33
  • Use DTE.ActiveDocument.Selection http://stackoverflow.com/questions/24402325/how-to-add-text-in-active-document-using-c-sharp – Sergey Vlasov Jun 11 '16 at 05:03

1 Answers1

1

I'll get you most the way there.

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

Now you have the caret position its on you to figure out what's there. Something like textView.GetTextElementSpan(caretPosition).GetText()

Paul Swetz
  • 2,234
  • 1
  • 11
  • 28