2010-05-19 40 views
7

hi tôi đang tạo phần mở rộng cho studio trực quan và điều cụ thể mà tôi cần là lấy văn bản được chọn của cửa sổ trình chỉnh sửa để xử lý tiếp. Ai đó biết giao diện hoặc dịch vụ nào có giao diện này? Trước đây tôi cần xác định đường dẫn của giải pháp mở và tôi yêu cầu một dịch vụ triển khai IVsSolution, vì vậy vấn đề khác tôi phải có một số dịch vụ cung cấp cho tôi thông tin này.lấy văn bản đã chọn của cửa sổ trình biên tập .. tiện ích mở rộng studio mở rộng

Trả lời

3

bên trong OnlayoutChanged đoạn mã sau sẽ bật lên một thông điệp với mã chọn:

if (_view.Selection.IsEmpty) 
     { 
      return; 
     } 
     else 
     { 
      string selectedText = _view.Selection.StreamSelectionSpan.GetText(); 

      MessageBox.Show(selectedText); 
     } 

bất cứ nơi nào khác chỉ nhận được viewhost và của nó _view loại (IWpfTextView)

10

Để làm rõ " chỉ cần có được viewhost "trong câu trả lời của Stacker, đây là mã đầy đủ cho cách bạn có thể có được giao diện trình soạn thảo hiện tại, và từ đó ITextSelection, từ bất cứ nơi nào khác trong Visual Studio 2010 VSPackage. Đặc biệt, tôi sử dụng điều này để có được lựa chọn hiện tại từ một lệnh gọi lại menu.

IWpfTextViewHost GetCurrentViewHost() 
{ 
    // code to get access to the editor's currently selected text cribbed from 
    // http://msdn.microsoft.com/en-us/library/dd884850.aspx 
    IVsTextManager txtMgr = (IVsTextManager)GetService(typeof(SVsTextManager)); 
    IVsTextView vTextView = null; 
    int mustHaveFocus = 1; 
    txtMgr.GetActiveView(mustHaveFocus, null, out vTextView); 
    IVsUserData userData = vTextView as IVsUserData; 
    if (userData == null) 
    { 
     return null; 
    } 
    else 
    { 
     IWpfTextViewHost viewHost; 
     object holder; 
     Guid guidViewHost = DefGuidList.guidIWpfTextViewHost; 
     userData.GetData(ref guidViewHost, out holder); 
     viewHost = (IWpfTextViewHost)holder; 
     return viewHost; 
    } 
} 


/// Given an IWpfTextViewHost representing the currently selected editor pane, 
/// return the ITextDocument for that view. That's useful for learning things 
/// like the filename of the document, its creation date, and so on. 
ITextDocument GetTextDocumentForView(IWpfTextViewHost viewHost) 
{ 
    ITextDocument document; 
    viewHost.TextView.TextDataModel.DocumentBuffer.Properties.TryGetProperty(typeof(ITextDocument), out document); 
    return document; 
} 

/// Get the current editor selection 
ITextSelection GetSelection(IWpfTextViewHost viewHost) 
{ 
    return viewHost.TextView.Selection; 
} 

Dưới đây là tài liệu MSDN cho IWpfTextViewHost, ITextDocument, và ITextSelection.

Các vấn đề liên quan