Export (0) Print
Expand All

VSPackage Tutorial 1: How to Create a VSPackage

You can add functionality to Visual Studio by creating a VSPackage. Because a VSPackage is a software module, it can be distributed to other people so that they can extend Visual Studio on their own computers.

By using the Visual Studio Integration Package Wizard, you can make a VSPackage project in Visual Studio that already has the source files and configuration files that are required to create a package. The project includes a file that defines a class that you name when you create the project. This class, which is derived from a Managed Package Framework (MPF) class named Package, includes attributes that determine how the VSPackage should work in Visual Studio. The Package class also contains initialization code and other code such as menu command handlers. This class is the foundation of the VSPackage.

This tutorial teaches how to create a new VSPackage and customize it, as follows:

  • Create a VSPackage by using the package wizard.

  • Implement a menu command handler.

  • Add a keyboard shortcut.

  • Add custom information to the Visual Studio splash screen and the About dialog box.

  • Obtain and use a Package Load Key (PLK).

NoteNote:

The steps in this tutorial are based on a C# project. However, except for specifics such as file name extensions and code, you can use the same steps for a Visual Basic project.

This tutorial is part of a series that teaches how to extend the Visual Studio integrated development environment (IDE). For more information, see Tutorials for Customizing Visual Studio By Using VSPackages.

In this section, you create a VSPackage solution in Visual Studio.

To create a basic VSPackage solution

  1. Open Visual Studio.

  2. On the File menu, point to New, and then click Project. In the New Project dialog box, expand Other Project Types, and then click Extensibility. Under Visual Studio installed templates, select Visual Studio Integration Package. Select Create Directory for Solution, and then, in the Name field, type First. Enter a location for the solution, for example, D:\ExtendVS.

    New Project dialog

    Click OK.

  3. On the wizard welcome page, click Next.

  4. On the Select a Programming Language page, select Visual C#, select Generate a new key file to sign the assembly, and then click Next.

  5. On the Basic VSPackage Information page, in the VSPackage name box, type FirstPackage, and accept the remaining defaults.

    Basic VSPackage information

    Click Next.

  6. On the Select VSPackage Options page, select Menu Command, and then click Next.

  7. On the Command Options page, in the Command name box, type First Command. (This text will appear on the menu in Visual Studio.) In the Command ID box, type cmdidFirstCommand. (This identifier will be used in the code to identify the command.)

    Command Options dialog

    Click Next.

  8. On the Select Test Options page, click Finish.

    The wizard creates a Visual Studio project that has basic functionality. You can try it by pressing F5, which builds the project and then opens it in another instance of Visual Studio in debugging mode (also known as the experimental build of Visual Studio).

    NoteNote:

    When you build the project the first time, Visual Studio may appear to hang and you may get a message that Visual Studio is busy. Just ignore the message and wait until Visual Studio opens and the package is loaded.

  9. In the experimental build, on the Tools menu, a command named First Command should be displayed. Notice that First Command is the name that you typed on the Command Options page of the wizard.

  10. Click First Command. A message that resembles the following one should appear.

    First Command Message Box

The message that is displayed when you click First Command on the Tools menu comes from code in the handler for the menu command. This handler is in the FirstPackage.cs file.

To examine the menu item handler

  1. In Solution Explorer, open FirstPackage.cs.

  2. Find the FirstPackage class. The FirstPackage class is defined as follows.

    public sealed class FirstPackage : Package
    

    Notice that the class is derived from the MPF Package class.

  3. Find the code for the menu handler, which is implemented by the MenuItemCallback method. The menu handler function is a typical Windows Forms event handler method.

    private void MenuItemCallback(object sender, EventArgs e)
    {
        IVsUIShell uiShell = (IVsUIShell)GetService(typeof(SVsUIShell));
        Guid clsid = Guid.Empty;
        int result;
        
        Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(
            uiShell.ShowMessageBox(
                0, ref clsid,
                "FirstPackage",
                string.Format(CultureInfo.CurrentCulture, 
                    "Inside {0}.MenuItemCallback()", this.ToString()),
                string.Empty, 0,
                OLEMSGBUTTON.OLEMSGBUTTON_OK,
                OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST,
                OLEMSGICON.OLEMSGICON_INFO,
                0, out result));
    }
    

By default, menu commands that are created by the package wizard do not have a keyboard shortcut. You can add one to First Command.

To add a default keyboard shortcut

  1. In Solution Explorer, open First.vsct.

    The file is opened in the XML editor in Visual Studio.

  2. Find the end of the Commands element, which is indicated by the </Commands> tag.

  3. Add the following lines between the </Commands> tag and the <Symbols> tag.

    <KeyBindings>
      <KeyBinding guid="guidFirstCmdSet" id="cmdidFirstCommand"    editor="guidVSStd97" key1="M" mod1="(control shift)"/>
    </KeyBindings>
    

    This KeyBinding element has several attributes. The guid and id attributes determine which command will receive the keyboard shortcut. The guid is the GUID of the VSPackage, and id is the command identifier that you typed when you ran the wizard. Both symbols are defined in the Symbols section, as follows.

    <Symbols>
      <GuidSymbol name="guidFirstCmdSet"     value="{600efde8-1f5e-4df5-bc22-06074a411975}">
        <IDSymbol name="cmdidFirstCommand" value="0x0100" />
      </GuidSymbol>
    

    The value of the editor attribute is a GUID that represents the context in which the keyboard shortcut will be available. In Visual Studio, the binding of a keyboard shortcut to a command can be scoped to particular windows or made global (that is, available everywhere in Visual Studio). For example, in a text editor, CTRL+I may run the Incremental Search command, but in Solution Explorer, CTRL+I has no key binding; therefore, CTRL+I is only available in the text editor. In this tutorial, the keyboard shortcut is designed to be global. Therefore, the value of the editor attribute is guidVSStd97, which is the value that makes a keyboard shortcut global.

    The key1 and mod1 attributes set the key and modifier that must be pressed to activate the keyboard shortcut. For the value of key1, all keys on the keyboard are available in symbolic form, for example, "M" for the letter M and "VK_F5" for the function key F5. The value of mod1 can be "Alt", "Control", or "Shift", separated by spaces, in any combination.

    In this tutorial, the value of key1 is M and the value of mod1 is (Control Shift). Therefore, the keyboard shortcut is CTRL+SHIFT+M.

  4. On the Debug menu, click Start without debugging.

    In the experimental build of Visual Studio, on the Tools menu, CTRL+SHIFT+M should be displayed next to First Command.

    First Command with Shortcut
  5. Press CTRL+SHIFT+M. You should see the same message that appears when you click First Command on the Tools menu.

    For more information about .vsct files, see VSCT XML Schema Reference.

You can include an icon and information about your package in the About dialog box. To do this, you must make the following changes to the solution:

The main VSPackage class uses the InstalledProductRegistration attribute to specify where to find information for the About dialog box. In this tutorial, the main class is named FirstPackage, and it can be modified by opening FirstPackage.cs.

The new project wizard generates the following InstalledProductRegistration attribute.

[InstalledProductRegistration(    false, "#110", "#112", "1.0", IconResourceID = 400)]

The resource IDs "#110" and "#112" refer to string resources that are defined in the VSPackage.resx file, as follows:

  • 110 refers to FirstPackage

  • 112 refers to Information about my VSPackage

IconResourceID 400 refers to the Package.ico file in the Resources folder, which is defined in the VSPackage.resx file as follows.

<data name="400" type="System.Resources.ResXFileRef,
  System.Windows.Forms">
  <value>Resources\Package.ico;System.Drawing.Icon, System.Drawing,
    Version=2.0.0.0, Culture=neutral,
    PublicKeyToken=b03f5f7f11d50a3a
  </value>

To customize the splash screen and the About dialog box, change the first argument of the InstalledProductRegistration attribute to true, so that your VSPackage can provide appropriate information through the IVsInstalledProduct interface.

To add custom information to the splash screen and the About dialog box

  1. Open FirstPackage.cs, find the InstalledProductRegistration attribute, and change its arguments as follows.

    [InstalledProductRegistration(true, null, null, null)] 
    
  2. Derive the FirstPackage class from both Package and IVsInstalledProduct.

    public sealed class FirstPackage : Package, IVsInstalledProduct
    
  3. Implicitly implement the IVsInstalledProduct interface by hovering the mouse over IVsInstalledProduct. When the IntelliSense menu appears, click the first item.

    Implement Interface

    Doing this adds the following stub methods to the FirstPackage class. In a later step, you will fill in the methods.

    public int IdBmpSplash(out uint pIdBmp)
    {
        throw new NotImplementedException();
    }
    public int IdIcoLogoForAboutbox(out uint pIdIco)
    {
        throw new NotImplementedException();
    }
    public int OfficialName(out string pbstrName)
    {
        throw new NotImplementedException();
    }
    public int ProductDetails(out string pbstrProductDetails)
    {
        throw new NotImplementedException();
    }
    public int ProductID(out string pbstrPID)
    {
        throw new NotImplementedException();
    }
    
  4. Copy GenericPackage.bmp and GenericPackage.ico from

    <Visual Studio SDK installation path>\VisualStudioIntegration\Samples\IDE\CSharp\Reference.Package\ and paste them in the Resources folder in the package solution.

  5. In Solution Explorer, right-click the Resources folder, point to Add, and then click Existing Item. Set the file type filter to All Files (*.*) and then add GenericPackage.bmp. Repeat this step to add GenericPackage.ico.

  6. In C:\ExtendVS\FirstPackage\FirstPackage\, right-click VSPackage.resx, and then click Open With. Select XML Editor and click OK to open the file in the XML editor.

  7. Add the following lines just before the final </root> tag.

    <data name="500" type="System.Resources.ResXFileRef,   System.Windows.Forms">
      <value>Resources\GenericPackage.bmp;    System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0,    Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a  </value>
    </data>
    <data name="600" type="System.Resources.ResXFileRef,   System.Windows.Forms">
      <value>Resources\GenericPackage.ico;    System.Drawing.Icon, System.Drawing, Version=2.0.0.0,    Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
      </value>
    </data>
    

    This markup declares the GenericPackage.bmp as resource ID 500, and GenericPackage.iso as resource ID 600.

  8. In FirstPackage.cs, replace the implementation of the IVsInstalledProduct interface by using the following code.

    public int IdBmpSplash(out uint pIdBmp) 
    { 
        pIdBmp = 500; 
        return Microsoft.VisualStudio.VSConstants.S_OK; 
    } 
    public int IdIcoLogoForAboutbox(out uint pIdIco) 
    { 
        pIdIco = 600; 
        return Microsoft.VisualStudio.VSConstants.S_OK; 
    } 
    public int OfficialName(out string pbstrName) 
    { 
        pbstrName = "My Package"; 
        return Microsoft.VisualStudio.VSConstants.S_OK; 
    } 
    public int ProductDetails(out string pbstrProductDetails) 
    { 
        pbstrProductDetails = "This is my package"; 
        return Microsoft.VisualStudio.VSConstants.S_OK; 
    } 
    public int ProductID(out string pbstrPID) 
    { 
        pbstrPID = "My Package ID"; 
        return Microsoft.VisualStudio.VSConstants.S_OK; 
    } 
    

    The first two methods return the resource IDs for the bitmap and icon. The remaining three functions return the name, product details, and product ID, so that they will appear in the About dialog box.

You can test the changes by completing the following procedure.

To test the splash screen and About dialog box customization

  1. In Solution Explorer, right-click the First project node, and then click Properties. The application designer appears.

  2. Click Debug. The Debug options pane appears.

  3. In the Command line arguments box, add the /splash switch.

    Command Line Splash Switch
  4. From the Visual Studio Command Prompt, running as administrator, type the following line into the Visual Studio Command Prompt:

    devenv.exe /ranu /rootsuffix Exp /setup

    This command may take a few minutes to complete.

  5. Press F5 to open Visual Studio in the experimental build.

    Splash screen

    The splash screen appears and displays the information about your VSPackage. Click OK to continue.

    Note   To prevent the splash screen from closing before you can read it, a simple dialog box appears in front of the splash screen. You can move the dialog box to better see the splash screen. Press OK to close the dialog box.

  6. On the Help menu, click About Microsoft Visual Studio.

    The About dialog box appears and displays the icon and text for your VSPackage.

    Help About dialog

When you distribute a VSPackage to other users, it must contain a resource named the Package Load Key (PLK). Except in the experimental build, Visual Studio cannot load VSPackages that do not contain a valid PLK.

In the experimental build, all VSPackages can be loaded so that they can be tested during development. To enable this, the Visual Studio SDK provides a special Developer Load Key (DLK). However, the Microsoft Software License Terms for the Visual Studio SDK do not allow you to redistribute the DLK.

For this tutorial, we will provide a PLK so that you do not have to obtain one on your own. A PLK value depends on the VSPackage GUID, which is derived from information that you supply when you create a VSPackage. To use the PLK that we provide for the package in this tutorial, you must change the VSPackage GUID to match the one that we used to generate the PLK.

To change the VSPackage GUID to match the provided PLK

  1. Open First.vsct and change the value of the GuidSymbol tag as follows.

    <GuidSymbol name="guidFirstPkg" value="{3fdab115-3cc1-457d-bd2a-78d72c7025be}" />
    
  2. Open Guids.cs and change the value of guidFirstPackageString.

    public const string guidFirstPkgString="3fdab115-3cc1-457d-bd2a-78d72c7025be";
    

To add the PLK to the VSPackage, complete the following procedure.

To add the PLK to the VSPackage

  1. In Solution Explorer, double-click VSPackage.resx to open it in the resource designer. A grid control appears.

  2. Add a resource and give it a unique number in the Name column, for example, 104. In the Value column, enter the following PLK. Enter it as an unbroken string.

    JEAPP8CCIKQCA0IRC9ZECMDRPZEZP2E3HPA9MRETM0CKJKK3JEKDAIDMKQR2EHK2CJKCQJKHAMQTAKDKIZPHM8KDCMC0AIEME0KAKAACCMM1QHH2ECEKH1JIQQIEZIPR

    Package Load Key Resource
  3. Open FirstPackage.cs and find the ProvideLoadKey attribute. Replace the last argument by using the resource name of the PLK, for example, 104.

    [ProvideLoadKey("Standard", "1.0", "FirstPackage", "Company", 104)]
    

To test the PLK, complete the following procedure.

To test the PLK

  1. In Solution Explorer, right-click the First project node, and then click Properties. The application designer appears.

  2. Click Debug. The Debug options pane appears.

  3. In the Command line arguments box, add /noVSIP. Doing this disables the DLK.

    Test Package Load Key with noVSIP
  4. Press F5 to open Visual Studio in the experimental mode.

  5. On the Help menu, click About Microsoft Visual Studio.

    The About dialog box appears and displays the icon and text for your VSPackage.

  6. Close the experimental build of Visual Studio.

  7. Change any letter in the PLK string resource.

  8. Press F5 to open Visual Studio in the experimental mode and then look at the About dialog box again.

    This time you should see a message that alerts you about a PLK load failure.

    Package Load Key Load Failure

When you are ready to distribute your VSPackage, you can obtain a PLK for it by visiting the the Visual Studio Extensibility Developer Center Web site. After you log on, follow the instructions to obtain a PLK. For more information, see How to: Obtain a PLK for a VSPackage.

Solution Explorer and the Task List are examples of tool windows. In VSPackage Tutorial 2: How to Create a Tool Window, you can create a tool window that docks in Visual Studio and lets you play music files.

Community Additions

ADD
Show:
© 2014 Microsoft