2016-06-10 2 views
-1

selected.Contains은 메서드를 호출하기 전에 사용자가 일부 코드를 선택 했어도 null 포인터 예외를 throw합니다.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

= (문자열) this.ServiceProvider.GetService (typeof (TextSelection)); 문제 야. 문자열이 null이고 그 이유는 Contains 메서드를 호출 할 수 없습니다. .GetService()가 반환하고 실제로 아무것도 반환합니까? 이후 그것은 null입니다. 자연스러운 변환이 아닐 수도 있습니다. –

+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

필요한 경우 표시하는 것을 잊지 마십시오. –

관련 문제