Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

hi i'm making a extension for visual studio and the specific thing that i need is get the selected text of the editor windows for further processing. Someone know what interface or service has this? Previously i need to locate the path of the open solution and for that i ask for a service that implements IVsSolution, so for this other problem I thing that there must be some service that provides me this information.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
331 views
Welcome To Ask or Share your Answers For Others

1 Answer

To clarify "just get the viewhost" in Stacker's answer, here is the full code for how you can get the current editor view, and from there the ITextSelection, from anywhere else in a Visual Studio 2010 VSPackage. In particular, I used this to get the current selection from a menu command callback.

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

Here's MSDN's docs for IWpfTextViewHost, ITextDocument, and ITextSelection.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...