次の方法で共有


Walkthrough: Creating a VSPackage (Part 1 of 4)

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 Package Template, you can make a project that already has the source files and configuration files that are required to create a VSPackage. 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 walkthrough teaches how to create a VSPackage and customize it, as follows:

  • Create a VSPackage by using the package template.

  • Implement a menu command handler.

  • Add a keyboard shortcut.

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

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

Prerequisites

To complete this walkthrough, you must install the Visual Studio 2010 SDK.

Note

For more information about the Visual Studio SDK, see Extending Visual Studio Overview. To find out how to download the Visual Studio SDK, see Visual Studio Extensibility Developer Center on the MSDN website.

Template Locations for the Visual Studio Package Template

The Visual Studio Package Template can be found in these locations in the New Project dialog box:

  1. Under Visual Basic Extensibility. The default language of the project is Visual Basic.

  2. Under C# Extensibility. The default language of the project is C#.

  3. Under Other Project Types Extensibility. The default language of the project is C++.

Creating a VSPackage By Using the Package Template

This section shows how to create a VSPackage solution in Visual Studio.

To create a basic VSPackage solution

  1. Create a VSPackage using the Visual Studio Package project template.

  2. On the welcome page, click Next.

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

  4. On the Basic VSPackage Information page, in the VSPackage name box, type FirstPackage, and accept the remaining defaults. The company name and the project name will be combined to create the namespace for the package.

    Basic VSPackage information

    Click Next.

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

  6. 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.

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

    The template 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).

    Note

    When you build the project the first time, Visual Studio may appear to stop responding 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.

  8. 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 template.

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

    First Command Message Box

Examining the Menu Command Handler

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 or FirstPackage.vb file.

To examine the menu item handler

  1. In Solution Explorer, open FirstPackage.cs or FirstPackage.vb.

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

    Public NotInheritable Class FirstPackage
        Inherits Package
    
    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 Sub MenuItemCallback(ByVal sender As Object, ByVal e As EventArgs)
            ' Show a Message Box to prove we were here
            Dim uiShell As IVsUIShell = TryCast(GetService(GetType(SVsUIShell)), IVsUIShell)
            Dim clsid As Guid = Guid.Empty
            Dim result As Integer
            Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(uiShell.ShowMessageBox(0, clsid, "FirstPackage", String.Format(CultureInfo.CurrentCulture, "Inside {0}.MenuItemCallback()", Me.GetType().Name), String.Empty, 0, OLEMSGBUTTON.OLEMSGBUTTON_OK, OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST, OLEMSGICON.OLEMSGICON_INFO, 0, result))
        End Sub
    
    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));
    }
    

Adding a Keyboard Shortcut

By default, menu commands that are created by the package template 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 template. 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 walkthrough, 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 walkthrough, 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.

Adding Custom Information to the About Dialog Box

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 walkthrough, the main class is named FirstPackage, and it can be modified by opening FirstPackage.cs or FirstPackage.vb.

The new project template generates the following InstalledProductRegistration attribute.

<InstalledProductRegistration(    false, "#110", "#112", "1.0", IconResourceID := 400)>
[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>
</data>

To customize 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 or FirstPackage.vb, find the InstalledProductRegistration attribute, and change its arguments as follows.

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

    Public NotInheritable Class FirstPackage
        Inherits Package
        Implements IVsInstalledProduct
    
    public sealed class FirstPackage : Package, IVsInstalledProduct
    
  3. Implicitly implement the IVsInstalledProduct interface. This step differs for C# and Visual Basic.

    1. In C#, 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();
      }
      
    2. In Visual Basic, add the following code to the bottom of the FirstPackage class. In a later step, you will fill in the methods.

      Function ProductDetails( _
          <OutAttribute()> ByRef pbstrProductDetails As String) _
      As Integer
      
      End Function
      
      Public Function IdBmpSplash(ByRef pIdBmp As UInteger) As Integer Implements Microsoft.VisualStudio.Shell.Interop.IVsInstalledProduct.IdBmpSplash
      
      End Function
      
      Public Function IdIcoLogoForAboutbox(ByRef pIdIco As UInteger) As Integer Implements Microsoft.VisualStudio.Shell.Interop.IVsInstalledProduct.IdIcoLogoForAboutbox
      
      End Function
      
      Public Function OfficialName(ByRef pbstrName As String) As Integer Implements Microsoft.VisualStudio.Shell.Interop.IVsInstalledProduct.OfficialName
      
      End Function
      
      Public Function ProductID(ByRef pbstrPID As String) As Integer Implements Microsoft.VisualStudio.Shell.Interop.IVsInstalledProduct.ProductID
      
      End Function
      
  4. Copy Icon.ico from <Visual Studio SDK installation path>\Common7\IDE\NewFileItems and paste it 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 Icon.ico.

  6. In Solution Explorer, 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.ico;    System.Drawing.Icon, System.Drawing, Version=2.0.0.0,    Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
      </value>
    </data>
    

    This markup declares Icon.ico as resource ID 500.

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

    Public Function ProductDetails(ByRef pbstrProductDetails As String) As Integer Implements IVsInstalledProduct.ProductDetails
        pbstrProductDetails = "This is my package"
        Return Microsoft.VisualStudio.VSConstants.S_OK
    End Function
    
    Public Function IdBmpSplash(ByRef pIdBmp As UInteger) _
    As Integer Implements IVsInstalledProduct.IdBmpSplash
        Return Microsoft.VisualStudio.VSConstants.S_OK
    End Function
    
    Public Function IdIcoLogoForAboutbox(ByRef pIdIco As UInteger) _
    As Integer Implements IVsInstalledProduct.IdIcoLogoForAboutbox
        pIdIco = 600
        Return Microsoft.VisualStudio.VSConstants.S_OK
    End Function
    
    Public Function OfficialName(ByRef pbstrName As String) _
    As Integer Implements IVsInstalledProduct.OfficialName
        pbstrName = "My Package"
        Return Microsoft.VisualStudio.VSConstants.S_OK
    End Function
    
    Public Function ProductID(ByRef pbstrPID As String) _
    As Integer Implements IVsInstalledProduct.ProductID
        pbstrPID = "My Package ID"
        Return Microsoft.VisualStudio.VSConstants.S_OK
    End Function
    
    public int IdBmpSplash(out uint pIdBmp) 
    { 
        return Microsoft.VisualStudio.VSConstants.S_OK; 
    } 
    public int IdIcoLogoForAboutbox(out uint pIdIco) 
    { 
        pIdIco = 500; 
        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 second method returns the resource ID for the 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. Press F5 to open Visual Studio in the experimental build.

  5. 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

What's Next

Solution Explorer and the Task List are examples of tool windows. In Walkthrough: Creating a Tool Window (Part 2 of 4), you can create a tool window that docks in Visual Studio and lets you play music files.

See Also

Concepts

Visual Studio Extensibility Samples

Other Resources

VSPackages

VSPackage Branding

VSPackage Load Keys

Reference.Package sample

Reference.Package sample