Customizing the Office 2007 Ribbon UI - Part 4

In this installment in the series on customizing the Ribbon UI, we'll look at adding application-level customization. In the previous blog, we detailed the steps to create document-level Ribbon by modifying an Open XML Formats macro-enabled file in Word 2007. In this blog, we will create application-level customizations using a managed COM add-in which we'll create in Microsoft Visual Studio 2005 using C#. For consistency, we'll use the same customization that we used in the previous blog; namely adding a custom tab, a custom group, and button that will insert a company name into a Word 2007 document at the beginning of the document. This is the procedure:

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

<customUI xmlns="https://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.

Now create the Visual C# project to modify the Ribbon UI:
1. Start Visual Studio .NET 2005.
2. On the File menu, click New Project.
3. In the New Project dialog box under Project Types, expand Other Projects, click Extensibility Projects, and then double-click Shared Addin.
4. Type a name for the project. In this sample, type RibbonXSampleCS.
5. In the first screen of the Shared Add-in Wizard, click Next.
6. In the next screen, select "Create an Add-in using Visual C#", and then click Next.
7. In the next screen, clear all of the selections except Microsoft Word and then click Next.
8. Type a Name and Description for the add-in, and then click Next.
9. In the Choose Add-in Options screen, select "I would like my Add-in to load when the host application loads" and then click Next.
10. Click Finish to complete the wizard.

Now add a reference to Word:
1. In the Solution Explorer, right-click References, and then click Add Reference.

Note: If you don't see the References folder, click the Project menu and then Show All Files.
 
2. Scroll downward on the .NET tab, press the Ctrl key, and then select Microsoft.Office.Interop.Word.
3. On the COM tab, scroll downward, select Microsoft Office 12.0 Object Library, and then click OK.
4. Next add the following namespace references to the project if they don't already exist. Do this just below the namespace line:

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;

Add the XML customization file as an embedded resource in the project by following these steps:
1. In the Solution Explorer, right-click RibbonXSampleCS, point to Add, and click Existing Item.
2. Navigate to the customUI.xml file you created, select the file, and then click Add.
3. In the Solution Explorer, right-click customUI.xml, and then select Properties.
4. In the properties window select Build Action, and then scroll down to Embedded Resource.

Next, to get access to its members, you need to implement the IRibbonExtensibility interface.
1. In the Solution Explorer, right-click Connect.cs, and click View Code.
2. Just below 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 Application object:

applicationObject =(MSword.Application)application;
 
4. At the end of the public class Connect statement, add a comma, and then type IRibbonExtensibility.

Tip: You can use Microsoft IntelliSense to insert interface methods for you. For example, at the end of the public class Connect : statement, type IRibbonExtensibility, right-click, point to Implement Interface, and then click Implement Interface Explicitly. This adds a stub for the only IRibbonExtensibility interface member: GetCustomUI. The implemented method looks like this:

string IRibbonExtensibility.GetCustomUI(string RibbonID)
{
}

5. Insert the following statement into the GetCustomUI method, overwriting the existing code:
            return GetResource("customUI.xml");

6. Insert the following method below the GetCustommUI method:

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

Note: 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 also construct a string that contains the XML markup and read it directly in 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.
            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);
        }

Compile both the add-in and its setup project. Before beginning, make sure that Word is closed.
1. In the Project menu, click Build Solution. You will see a message when the build is complete in the system tray in the lower left corner of the window.
2. In the Solution Explorer, right-click RibbonXSampleCSSetup and click Build.
3. Right-click RibbonXSampleCSSetup and click Install. This launches the RibbonXSampleCSSetup Setup Wizard screen.
4. Click Next on all of the screens and then Close on the final screen.
5. Start Word. You should see the "My Tab" tab to the right of the other tabs.

To test the project:
Click the "My tab" tab and then click the "Insert Company Name" button. The company name is inserted into the document at the cursor location.

If you don’t see the customized Ribbon UI, you may need to add an entry to the registry. To do this, perform the following steps:

Caution: The next few steps contain information about modifying 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. For information about how to back up, restore, and edit the registry, search for the following article in the Microsoft Knowledge Base: 256986 Description of the Microsoft Windows Registry.

1. In the Solution Explorer, right click on the setup project, RibbonXSampleCSSetup, point to View, and then click Registry.
2. From the Registry tab, navigate to the following registry key for the add-in:

HKCU\Software\Microsoft\Office\Word\AddIns\RibbonXSampleCS.Connect

Note: If the RibbonXSampleCS.Connect key does not exist, you can create it. To do so, right-click the Addins folder, point to New, and then click Key. Name the key RibbonXSampleCS.Connect. Add a LoadBehavior DWord and set its value to 3.

And that's all there is to creating a COM Add-in to customize the Ribbon UI. In the next blog in this series, we'll look at customizing the Ribbon UI by using a COM add-in created in Visual Basic.