Search code examples
c#visual-studio-2015selectedtext

How could I get user selected code in Visual Studio 2015


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

Solution

  • 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()