Search code examples
c#visual-studiovisual-studio-extensions

Visual Studio Extension: Get Package from adornment


I'm developing a Visual Studio Extension, made up of:

  1. A menu and series of commands
  2. A tools window
  3. One or more textview adornments
  4. A custom implementation of AysncPackage

Now, while the Tools Window and the commands are either wired up by, or have a handle on, the AsyncPackage for my extension, what I cannot figure out is HOW I get a handle to the self-same AsyncPackage from one or more of my text adornments.

For example, my Tools Window extends ToolWindowPane, which has a hook to the Package via the Package's ProvideToolWindow attribute. My commands are constructed inside the Package itself, so passing a handle to the AsyncPackage is simple enough.

What I cannot work out is HOW you get a reference to this AsyncPackage inside any of my TextAdornments.

Any help?


Solution

  • This was a tricky one! You must get the IVsShell to retrieve a package based on a GUID you associate with your Package, and then cast it to your interface (or the base interface of IPackage)

     private IMyPackageInterface _myPackage;
    
     //let's get our hands on that package
    var vsShell = (IVsShell) ServiceProvider.GlobalProvider.GetService(typeof(IVsShell));
    if (vsShell == null)
    {
        throw new NullReferenceException();
    }
    
    if (vsShell.IsPackageLoaded(PackageGuid, out var myPossiblePackage) 
        == Microsoft.VisualStudio.VSConstants.S_OK) { 
    _myPackage = (IMyPackageInterface)myPossiblePackage;