Personalizar a faixa de opções do Office Fluent usando um suplemento de COM gerenciado

The ribbon component of the Microsoft Office Fluent user interface in Microsoft Office suites gives users a flexible way to work with Office applications. Ribbon Extensibility (RibbonX) uses simple, text-based, declarative XML markup to create and customize the ribbon.

The code example in this topic shows how to customize the ribbon in an Office application, no matter what document is open. In the following steps, you create application-level customizations by using a managed COM add-in, and you create the add-in in Microsoft Visual Studio 2012 by using Microsoft Visual C#. The project adds a custom tab, a custom group, and a custom button to the ribbon. To complete the procedure, you perform the following tasks.

  1. Create the XML customization file.

  2. Create a managed COM add-in project in Microsoft Visual Studio 2012 with C#.

  3. Add the XML customization file to the project as an embedded resource.

  4. Implement the IRibbonExtensibility interface.

  5. Crie um método de retorno de chamada que é disparado quando o botão é escolhido.

  6. Build, install, and test the project.

Criar o arquivo de personalização XML

In this step, you create the file that adds the custom components to the ribbon.

  1. In a text editor, add the following XML markup.

     <customUI xmlns="http://schemas.microsoft.com/office/2006/01/customui"> 
       <ribbon> 
         <tabs> 
           <tab id="CustomTab" label="My Tab"> 
             <group id="SampleGroup" label="Sample Group"> 
               <button id="Button" label="Insert Company Name" size="large" onAction="InsertCompanyName" /> 
             </group > 
           </tab> 
         </tabs> 
       </ribbon> 
     </customUI> 
    
  2. Close and save the file as customUI.xml.

Criar um projeto de suplemento COM gerenciado

In this step, you create a COM add-in C# project in Microsoft Visual Studio 2012.

  1. Inicie Microsoft Visual Studio 2012.

  2. No menu Arquivo , escolha Novo Projeto.

  3. Na caixa de diálogo Novo Projeto em Tipos de Projeto, expanda Outros Projetos, escolha Projetos de Extensibilidade e clique duas vezes em Suplemento Compartilhado.

  4. Add a name for the project; for this sample, type RibbonXSampleCS.

  5. Na primeira tela do Assistente de Suplemento Compartilhado, escolha Avançar.

  6. Selecione Criar um Suplemento usando o Visual C#e escolha Avançar.

  7. Desmarque todas as seleções, exceto Microsoft Word e escolha Avançar.

  8. Digite um nome e uma descrição para o suplemento e escolha Avançar.

  9. Na tela Escolher Opções de Suplemento , selecione Gostaria que meu Suplemento fosse carregado quando o aplicativo host for carregado e escolha Avançar.

  10. Escolha Concluir para concluir o assistente.

Adicionar referências externas ao projeto

Nesta etapa, você adicionará referências a Assemblies de Interoperabilidade Primária do Word e à biblioteca de tipos.

  1. No Gerenciador de Soluções, clique com o botão direito do mouse em Referências e escolha Adicionar Referência.

    Observação

    Se você não vir a pasta Referências , escolha o menu Projeto e escolha Mostrar Todos os Arquivos.

  2. Scroll down on the .NET tab, press the CTRL key, and then select Microsoft.Office.Interop.Word.

  3. Na guia COM , role para baixo, selecione a Biblioteca de Objetos do Microsoft Office 15.0 (ou a biblioteca apropriada para sua versão do Office) e escolha OK.

  4. Adicione as referências de namespace a seguir ao projeto, se elas ainda não existirem, logo abaixo da linha namespace .

     using System.Reflection; 
     using Microsoft.Office.Core; 
     using System.IO; 
     using System.Xml; 
     using Extensibility; 
     using System.Runtime.InteropServices; 
     using MSword = Microsoft.Office.Interop.Word; 
    

Adicionar o arquivo de personalização XML como um recurso inserido

In this step, you add the XML customization file as an embedded resource in the project.

  1. No Gerenciador de Soluções, clique com o botão direito do mouse em RibbonXSampleCS, aponte para Adicionar e escolha Item Existente.

  2. Navegue até o arquivo customUI.xml que você criou, selecione o arquivo e escolha Adicionar.

  3. In the Solution Explorer, right-click customUI.xml, and then select Properties.

  4. No janela Propriedades, selecione Criar Ação e role para baixo até o Recurso Incorporado.

Implementar a interface IRibbonExtensibility

In this step you add code to the Extensibility.IDTExtensibility2::OnConnection to create a reference to the Word application at runtime. You also implement the only member of the IRibbonExtensibility interface, GetCustomUI.

  1. No Gerenciador de Soluções, clique com o botão direito do mouse em Connect.cs e escolha Exibir Código.

  2. After the Connect method, add the following declaration, which creates a reference to the Word Application object:

    private MSword.Application applicationObject;

  3. Add the following line to the OnConnection method. This statement creates an instance of the Word Application object:

    applicationObject =(MSword.Application)application;

  4. No final da instrução connect de classe pública, adicione uma vírgula e digite IRibbonExtensibility.

    Observação

    Use o Microsoft IntelliSense para inserir métodos de interface para você. Por exemplo, no final da instrução Connect de classe pública, digiteIRibbonExtensibility, clique com o botão direito do mouse e aponte para Implementar Interface e escolha Implementar Interface explicitamente. This adds a stub for the GetCustomUI method. The implementation looks similar to the following code.

       string IRibbonExtensibility.GetCustomUI(string RibbonID) 
     { 
     }
    
  5. Insira a seguinte instrução no método GetCustomUI , substituindo o código existente: return GetResource("customUI.xml");

  6. Insira o seguinte método abaixo do método GetCustomUI :

     private string GetResource(string resourceName) 
           { 
               Assembly asm = Assembly.GetExecutingAssembly(); 
               foreach (string name in asm.GetManifestResourceNames()) 
               { 
                   if (name.EndsWith(resourceName)) 
                   { 
                       System.IO.TextReader tr = new System.IO.StreamReader(asm.GetManifestResourceStream(name)); 
                       //Debug.Assert(tr != null); 
                       string resource = tr.ReadToEnd(); 
    
                       tr.Close(); 
                       return resource; 
                   } 
               } 
               return null; 
           } 
    
    

    The GetCustomUI method calls the GetResource method. The GetResource method sets a reference to this assembly during runtime and then loops through the embedded resource until it finds the one named customUI.xml. It then creates an instance of the StreamReader object that reads the embedded file containing the XML markup. The procedure passes the XML back to the GetCustomUI method which returns the XML to the ribbon. Alternately, you can construct a string that contains the XML markup and read it directly into the GetCustomUI method.

  7. Following the GetResource method, add this method. This method inserts the company name into the document at the beginning of the page.

     public void InsertCompanyName(IRibbonControl control) 
           { 
           // Inserts the specified text at the beginning of a range or selection. 
               string MyText; 
               MyText = "Microsoft Corporation"; 
    
               MSword.Document doc = applicationObject.ActiveDocument; 
    
               //Inserts text at the beginning of the active document. 
               object startPosition = 0; 
               object endPosition = 0; 
               MSword.Range r = (MSword.Range)doc.Range( 
                     ref startPosition, ref endPosition); 
               r.InsertAfter(MyText); 
           } 
    
    

Criar e instalar o projeto

In this step, you build the add-in and its setup project. Before you continue, make sure that Word is closed.

  1. No menu Projeto , escolha Criar solução. When the build is complete, a notification appears in the lower left corner of the window.

  2. No Gerenciador de Soluções, clique com o botão direito do mouse em RibbonXSampleCSSetup e escolha Compilar.

  3. Clique com o botão direito do mouse em RibbonXSampleCSSetup novamente e escolha Instalar para iniciar o Assistente de Instalação RibbonXSampleCSSetup.

  4. Escolha Avançar em cada uma das telas e escolha Fechar na tela final.

  5. Inicie o Word. You should see the My Tab tab to the right of the other tabs.

Testar o projeto

Escolha a guia Minha Guia e escolha Inserir Nome da Empresa para inserir o nome da empresa no documento no cursor. Se você não vir a faixa de opções personalizada, talvez seja necessário adicionar uma entrada ao registro do Windows concluindo as etapas a seguir.

Cuidado

[!CUIDADO] The next few steps contain information about how to modify the registry. Before you modify the registry, be sure to back it up and make sure that you understand how to restore the registry if a problem occurs. Para obter mais informações sobre como fazer backup, restaurar e editar o registro, confira este artigo da Base de Dados de Conhecimento da Microsoft: informações de registro do Windows para usuários avançados (256986).

  1. No Gerenciador de Soluções, clique com o botão direito do mouse no projeto de instalação, RibbonXSampleCSSetup, aponte para Exibição e escolha Registro.

  2. From the Registry tab, navigate to the following registry key for the add-in: HKCU\Software\Microsoft\Office\Word\AddIns\RibbonXSampleCS.Connect

    Observação

    [!OBSERVAçãO] If the RibbonXSampleCS.Connect key does not exist, you can create it. Para fazer isso, clique com o botão direito do mouse na pasta Addins , aponte para Novo e escolha Chave. Name the key RibbonXSampleCS.Connect. Adicione um DWord loadBehavior e defina seu valor como 3.

Confira também

Suporte e comentários

Tem dúvidas ou quer enviar comentários sobre o VBA para Office ou sobre esta documentação? Confira Suporte e comentários sobre o VBA para Office a fim de obter orientação sobre as maneiras pelas quais você pode receber suporte e fornecer comentários.