Notice: This website is an unofficial Microsoft Knowledge Base (hereinafter KB) archive and is intended to provide a reliable access to deleted content from Microsoft KB. All KB articles are owned by Microsoft Corporation. Read full disclaimer for more details.

How to use the CommandBars object in a managed code solution in InfoPath


View products that this article applies to.

Summary

In Microsoft Office 2003 Service Pack 1, and in 2007 Microsoft Office, and in Microsoft Visual Studio .NET 2003, you can create managed code that targets a Microsoft Office InfoPath 2003 form template or a Microsoft Office InfoPath 2007 form template. You can use that managed code to make a change to the CommandBars object that InfoPath 2003 or InfoPath 2007 uses for menus and for toolbars. To do this, you have to create a Microsoft Visual C# .NET InfoPath project. Then, you have to write code to access and to control the CommandBars object.

↑ Back to the top


Introduction

This article describes how to create a project that adds a new toolbar with a button to an InfoPath 2007 form or to an InfoPath 2003 form.

Note You must have Microsoft Office InfoPath 2003 Toolkit for Visual Studio .NET or InfoPath 2007 installed.

↑ Back to the top


More information

Create the Visual C# .NET InfoPath 2007 project

In InfoPath 2007, you can create the project in Visual Studio Tools for Applications. To create the project, you must set the programming language to C#, add a reference to the Microsoft Office 12.0 Object Library, and then add the given code. To do this, follow these steps.

Set the programming language

Warning The Remove Code command that is mentioned in the following steps removes all the existing code from the current form. Therefore, do not use this command unless you are sure that you want to perform this action.
  1. In InfoPath, click File, and then click Design a Form Template.
  2. In the Design a Form Template dialog box, click Blank, and then click OK.
  3. In InfoPath 2007, click Form Options on the Tools menu.
  4. In the Category list, click Programming.
  5. If the Form template code language box is unavailable, click Remove Code to remove all the existing code in the form. If the Form template code language box is available, go to the next step.
  6. In the Form template code language box, click C#, and then click OK.

Add an "Add Command Bars" button to the InfoPath 2007 form template

  1. In InfoPath 2007, click Controls on the Design Tasks task pane.
  2. Locate a button in the Standard controls task pane. Add that button to the form.
  3. Right-click the new button, and then click Button Properties.
  4. In the Button Properties dialog box, set Label to Add Command Bars , and then set ID to AddCommandBar.
  5. Click Edit Form Code.
  6. In Visual Studio, right-click Reference in the Project Explorer pane, and then click Add Reference.
  7. In the Add Reference dialog box, click the COM tab.
  8. Under Component name, double-click Microsoft Office 12 Object Library, and then click OK.
  9. In Visual Studio, type using Microsoft.Office.Core; under using Microsoft.Office.InfoPath; at the top of the Formcode.cs file.
  10. Under the last // Write your code here section, enter the following code.
     CommandBars commandBars = (CommandBars)this.Application.ActiveWindow.CommandBars;
    
                Microsoft.Office.Core.CommandBar formBar = commandBars["Standard"];
    
                CommandBarButton newButton = (CommandBarButton)formBar.Controls.Add(MsoControlType.msoControlButton, Type.Missing, Type.Missing, Type.Missing, true);
    
                newButton.Caption = "Click Me";
    
                newButton.Visible = true;
    
                newButton.Enabled = true;
    
                newButton.Style = MsoButtonStyle.msoButtonCaption;
    
                newButton.Click += new _CommandBarButtonEvents_ClickEventHandler(newButton_Click);
    
    
            }
            public void newButton_Click(CommandBarButton btn, ref bool cancel)
            {
    
                MessageBox.Show("Hello World");
    
            }

Create the Visual C# .NET InfoPath 2003 project

To create a sample InfoPath 2003 form template that uses managed code to add a new toolbar with a button, follow these steps:
  1. Start Visual Studio .NET 2003.
  2. On the File menu, click New, and then click Project.
  3. In the New Project dialog box, click Visual C# Projects in the Microsoft Office InfoPath Projects folder.
  4. Name the new project ManagedCommandBars, and then click OK.
  5. In the Microsoft Office Project Wizard dialog box, click Create a new form template, and then click Finish.

    The Microsoft Office Project Wizard creates a new Visual Studio .NET 2003 project that is named ManagedCommandBars. An InfoPath 2003 form template is also created. The InfoPath 2003 form template is named ManagedCommandBars.
  6. In Solution Explorer, right-click References in the ManagedCommandBars project, and then click Add Reference.
  7. In the Add Reference dialog box, click Select to add a reference to the office component on the .NET tab, and then click OK.
  8. Find the following code in the Formcode.cs file of the ManagedCommandBars Visual Studio .NET 2003 project:
    using System;
    Replace the previous code with the following code:
    using System;
    using System.Reflection;

Add code to unwrap the CommandBars object

The CommandBars collection in the InfoPath 2003 object model is wrapped in a Microsoft.Office.Interop.InfoPath.SemiTrust.ObjectWrapper object. To use the CommandBars collection, you must unwrap the CommandBars object.

To unwrap the CommandBars object, find the following function in the Formcode.cs file of the ManagedCommandBars project:
public void _Shutdown()
{
}
Replace the previous code with the following code:
public void _Shutdown()
{
}

//The following function unwraps the CommandBars object so that the CommandBars object
//is easier to use in the code.
private Microsoft.Office.Core.CommandBars UnwrapCommandbarsObject( 
   Microsoft.Office.Interop.InfoPath.SemiTrust.ObjectWrapper commandBarsWrapper )
{
   //Get the System.Type object for the CommandBars wrapper object.
   Type t = commandBarsWrapper.GetType().BaseType;

   //Use the Type object to retrieve the InnerObject property of the wrapper.
   Microsoft.Office.Core.CommandBars objCommandBars = 
      (Microsoft.Office.Core.CommandBars)t.InvokeMember( "InnerObject",
      BindingFlags.Public | BindingFlags.NonPublic |
      BindingFlags.Instance | BindingFlags.GetProperty,
      null, commandBarsWrapper, null);

   //Return the result.
   return objCommandBars;
}

Add an "Add Command Bars" button to the InfoPath 2003 form template

  1. In the ManagedCommandBars InfoPath 2003 form template, click Controls in the Design Tasks task pane.
  2. Locate a button in the Standard controls task pane. Add that button to the form.
  3. Right-click the new button, and then click Button Properties.
  4. In the Button Properties dialog box, type Add Command Bars in the Label box, and then type AddCommandBar in the ID box.
  5. Click Edit Form Code.

    A new InfoPathEventHandler function is added to the ManagedCommandBars Visual Studio .NET 2003 project.
  6. In the Formcode.cs file of the ManagedCommandBars project, find the following function:
    // The following function handler is created by InfoPath. Do not
    // modify the type or the number of arguments.
    [InfoPathEventHandler(MatchPath="AddCommandBar", EventType=InfoPathEventType.OnClick)]
    public void AddCommandBar_OnClick(DocActionEvent e)
    {
       // Write your code here.
       
    }
    
    Replace the previous code with the following code:
    // The following function handler is created by InfoPath. Do not
    // modify the type or the number of arguments.
    [InfoPathEventHandler(MatchPath="AddCommandBar", EventType=InfoPathEventType.OnClick)]
    public void AddCommandBar_OnClick(DocActionEvent e)
    {
       Object oMissing = System.Reflection.Missing.Value;
       Microsoft.Office.Core.CommandBars objCommandBars = null;
       Microsoft.Office.Core.CommandBar oCommandBar = null;
    
       try
       {
          //Get a reference to the CommandBars collection. The CommandBars 
          //collection is defined in the Microsoft Office 11.0 Object Library.
          //The CommandBars collection is in a wrapper object. Unwrap the CommandBars collection.
          objCommandBars = UnwrapCommandbarsObject( (ObjectWrapper)
             thisXDocument.View.Window.CommandBars );
       }
       catch (System.Exception ex)
       {
          thisXDocument.UI.Alert( ex.Message );
       }
    
       //Find the Example CommandBars command bar.
       try
       {
          oCommandBar = objCommandBars["Example CommandBar"];
       }
       catch(System.Exception ex)
       {
          //Create a new CommandBar.
          oCommandBar = objCommandBars.Add( 
             "Example CommandBar", oMissing, oMissing, oMissing);
    
          //Add a button to the CommandBar.
          oButton = (Microsoft.Office.Core.CommandBarButton)oCommandBar.Controls.
             Add( Microsoft.Office.Core.MsoControlType.msoControlButton, oMissing,
             oMissing, oMissing, oMissing );
    
          //Set the caption and the face ID.
          oButton.Caption = "Click Me";
          oButton.Style = Microsoft.Office.Core.MsoButtonStyle.msoButtonCaption;
    
          //Set up a delegate for the Click event.
          Microsoft.Office.Core._CommandBarButtonEvents_ClickEventHandler oButtonHandler = 
             new Microsoft.Office.Core._CommandBarButtonEvents_ClickEventHandler( 
             oButton_Click );
          oButton.Click += oButtonHandler;
       }
    
       //Show the CommandBars to the user.
       oCommandBar.Visible = true;
    }
    
    //This is the CommandBarButton declaration.
    Microsoft.Office.Core.CommandBarButton oButton;
    
    private void oButton_Click(Microsoft.Office.Core.CommandBarButton Ctrl, 
       ref bool Cancel)
    {
       // Reset all values.
       thisXDocument.UI.Alert("Hello, World!");
    }

Add a "Remove Command Bars" button to the InfoPath 2003 form template

  1. In the Design Tasks task pane, click Controls.
  2. In the ManagedCommandBars InfoPath 2003 form template, locate a button in the Standard controls task pane. Add that button to the form.
  3. Right-click the new button, and then click Button Properties.
  4. In the Button Properties dialog box, set Label to Remove Command Bars, and then set ID to RemoveCommandBar.
  5. Click Edit Form Code.

    A new InfoPathEventHandler function is added in the ManagedCommandBars Visual Studio .NET 2003 project.
  6. In the Formcode.cs file of the ManagedCommandBars project, find the following function:
    // The following function handler is created by InfoPath. Do not
    // modify the type or the number of arguments.
    [InfoPathEventHandler(MatchPath="RemoveCommandBar", EventType=InfoPathEventType.OnClick)]
    public void RemoveCommandBar_OnClick(DocActionEvent e)
    {
       // Write your code here.
       
    }
    
    Replace the previous code with the following code:
    // The following function handler is created by InfoPath. Do not
    // modify the type or the number of arguments.
    [InfoPathEventHandler(MatchPath="RemoveCommandBar", EventType=InfoPathEventType.OnClick)]
    public void RemoveCommandBar_OnClick(DocActionEvent e)
    {
       try
       {
          //Get a reference to the CommandBars collection. The CommandBars 
          //collection is defined in the Microsoft Office 11.0 Object Library.
          //The CommandBars collection is in a wrapper object. Unwrap the CommandBars collection.
          Microsoft.Office.Core.CommandBars objCommandBars = 
             UnwrapCommandbarsObject( (ObjectWrapper)
             thisXDocument.View.Window.CommandBars );
    
          //Find the Example CommandBar CommandBars.
          Microsoft.Office.Core.CommandBar oCommandBar = 
             objCommandBars["Example CommandBar"];
    
          //Delete the CommandBars.
          oCommandBar.Delete();
       }
       catch (System.Exception ex)
       {
          thisXDocument.UI.Alert( ex.Message );
       }
    }

Make sure that the form template is fully trusted

To use the CommandBars collection, the form template must be fully trusted. You can use any one of the following options to make sure that your form template is fully trusted:
  • Use the Microsoft .NET Framework 1.1 Configuration utility to grant Full Trust permissions only to your Visual C# .NET code.
  • Use the RegForm utility from the InfoPath 2003 Software Development Kit (SDK) to make your InfoPath 2003 form a fully trusted form. This in turn grants Full Trust permissions to your Visual C# .NET code.
  • Digitally sign your form template file (.xsn) by using a code-signing certificate. When you use a code-signing certificate to digitally sign your form template file, users are prompted to trust the form when they open the form. This makes your form fully trusted. Therefore, Full Trust permissions are granted to your Visual C# .NET code.
  • Use external Automation in InfoPath 2003 to call the RegisterSolution method.

    Typically, this last option is only used for form development. This is because a registered form only registers for your individual computer. For any additional forms, another user must register the additional forms on their own computer. We do not recommend this option for additional forms. We recommend any one of the three previous options when you publish your form.
Because this form is under form development, you can use the last option. To do this, locate the ManagedCommandBars InfoPath 2003 form template and then follow these steps:
  1. On the Tools menu, click Form Options.
  2. Click Security.
  3. Click to clear the Automatically determine security level based on form's design (recommended) check box.

    Note InfoPath 2003 cannot automatically detect business logic that requires Full Trust permissions. Therefore, you must explicitly give Full Trust permissions.
  4. Click Full Trust, and then click OK.
  5. Close the ManagedCommandBars InfoPath 2003 form template. Do not close the Visual Studio .NET 2003 project. If you are prompted to save changes, click Yes.
  6. In Visual Studio .NET 2003, double-click the Manifest.xsf file in the Solution Explorer window.

    The Manifest.xsf file opens.
  7. In the root node, locate the publishUrl attribute. Remove the publishUrl attribute and its value.
  8. Save your changes.
  9. Open a text editor, such as Notepad.
  10. Add the following code to the blank text file:
    oApp = WScript.CreateObject("InfoPath.ExternalApplication");
    strAbsolutePath = "<project_folder_url>\\Manifest.xsf";
    oApp.RegisterSolution(strAbsolutePath,"overwrite");
    Note Replace <project_folder_url> with the path of the Manifest.xsf file in your project folder. Remember to escape the path of the Manifest.xsf file. All single backslashes (\) in the path must be replaced with two backslashes (\\).
  11. Save the Manifest.xsf file on your computer as Register.js
  12. Double-click the Register.js file that you just created to call the RegisterSolution method.

Test the form

  1. In the ManagedCommandBars Visual Studio .NET 2003 project, click Start on the Debug menu.

    This starts the InfoPath 2003 form in Preview mode.
  2. On the InfoPath 2003 form, click Add Command Bar.

    Notice that a new toolbar appears.
  3. On the new toolbar, click Click Me.

    Notice that "Hello, World!" appears in the message box.
  4. In the message box, click OK.
  5. Click Remove Command Bar.

    Notice that the new command bar is deleted.
  6. Click Close Preview to end the test.

↑ Back to the top


References

For more information about Microsoft Office InfoPath 2003 Toolkit for Visual Studio .NET, visit the following Microsoft Web site:

↑ Back to the top


Keywords: KB867442, kbhowto

↑ Back to the top

Article Info
Article ID : 867442
Revision : 5
Created on : 9/22/2011
Published on : 9/22/2011
Exists online : False
Views : 366