Microsoft KB Archive/867442

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

Article ID: 867442

Article Last Modified on 6/19/2007

-

APPLIES TO


 * Microsoft Office InfoPath 2003, Service Pack 1 (SP1)
 * Microsoft Office InfoPath 2007

-



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.



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.



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 &quot;Add Command Bars&quot; button to the InfoPath 2007 form template
 In InfoPath 2007, click Controls on the Design Tasks task pane. Locate a button in the Standard controls task pane. Add that button to the form. Right-click the new button, and then click Button Properties. In the Button Properties dialog box, set Label to Add Command Bars, and then set ID to AddCommandBar. Click Edit Form Code. In Visual Studio, right-click Reference in the Project Explorer pane, and then click Add Reference. In the Add Reference dialog box, click the COM tab.</li> Under Component name, double-click Microsoft Office 12 Object Library, and then click OK.</li> In Visual Studio, type using Microsoft.Office.Core; under using Microsoft.Office.InfoPath; at the top of the Formcode.cs file.</li>  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[&quot;Standard&quot;];

CommandBarButton newButton = (CommandBarButton)formBar.Controls.Add(MsoControlType.msoControlButton, Type.Missing, Type.Missing, Type.Missing, true);

newButton.Caption = &quot;Click Me&quot;;

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(&quot;Hello World&quot;);

} </li></ol>

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: <ol> Start Visual Studio .NET 2003.</li> On the File menu, click New, and then click Project.</li> In the New Project dialog box, click Visual C# Projects in the Microsoft Office InfoPath Projects folder.</li> Name the new project ManagedCommandBars, and then click OK.</li> 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.</li> In Solution Explorer, right-click References in the ManagedCommandBars project, and then click Add Reference.</li> In the Add Reference dialog box, click Select to add a reference to the office component on the .NET tab, and then click OK.</li>  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; </li></ol>

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( &quot;InnerObject&quot;,     BindingFlags.Public | BindingFlags.NonPublic |      BindingFlags.Instance | BindingFlags.GetProperty,      null, commandBarsWrapper, null);

//Return the result. return objCommandBars; }

Add an &quot;Add Command Bars&quot; button to the InfoPath 2003 form template
<ol> In the ManagedCommandBars InfoPath 2003 form template, click Controls in the Design Tasks task pane.</li> Locate a button in the Standard controls task pane. Add that button to the form.</li> Right-click the new button, and then click Button Properties.</li> In the Button Properties dialog box, type Add Command Bars in the Label box, and then type AddCommandBar in the ID box.</li> <li>Click Edit Form Code.

A new InfoPathEventHandler function is added to the ManagedCommandBars Visual Studio .NET 2003 project.</li> <li> 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=&quot;AddCommandBar&quot;, 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=&quot;AddCommandBar&quot;, 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[&quot;Example CommandBar&quot;]; }  catch(System.Exception ex) {     //Create a new CommandBar. oCommandBar = objCommandBars.Add(         &quot;Example CommandBar&quot;, 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 = &quot;Click Me&quot;; 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(&quot;Hello, World!&quot;); } </li></ol>

Add a &quot;Remove Command Bars&quot; button to the InfoPath 2003 form template
<ol> <li>In the Design Tasks task pane, click Controls.</li> <li>In the ManagedCommandBars InfoPath 2003 form template, locate a button in the Standard controls task pane. Add that button to the form.</li> <li>Right-click the new button, and then click Button Properties.</li> <li>In the Button Properties dialog box, set Label to Remove Command Bars, and then set ID to RemoveCommandBar.</li> <li>Click Edit Form Code.

A new InfoPathEventHandler function is added in the ManagedCommandBars Visual Studio .NET 2003 project.</li> <li> 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=&quot;RemoveCommandBar&quot;, 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=&quot;RemoveCommandBar&quot;, 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[&quot;Example CommandBar&quot;];

//Delete the CommandBars. oCommandBar.Delete; }  catch (System.Exception ex) {     thisXDocument.UI.Alert( ex.Message ); } } </li></ol>

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: <ol> <li>On the Tools menu, click Form Options.</li> <li>Click Security.</li> <li>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.</li> <li>Click Full Trust, and then click OK.</li> <li>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.</li> <li>In Visual Studio .NET 2003, double-click the Manifest.xsf file in the Solution Explorer window.

The Manifest.xsf file opens.</li> <li>In the root node, locate the publishUrl attribute. Remove the publishUrl attribute and its value.</li> <li>Save your changes.</li> <li>Open a text editor, such as Notepad.</li> <li> Add the following code to the blank text file: oApp = WScript.CreateObject(&quot;InfoPath.ExternalApplication&quot;); strAbsolutePath = &quot;<project_folder_url>\\Manifest.xsf&quot;; oApp.RegisterSolution(strAbsolutePath,&quot;overwrite&quot;); Note Replace  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 (\\). </li> <li>Save the Manifest.xsf file on your computer as Register.js</li> <li>Double-click the Register.js file that you just created to call the RegisterSolution method.</li></ol>

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.
 * 1) On the InfoPath 2003 form, click Add Command Bar.

Notice that a new toolbar appears.
 * 1) On the new toolbar, click Click Me.

Notice that &quot;Hello, World!&quot; appears in the message box.
 * 1) In the message box, click OK.
 * 2) Click Remove Command Bar.

Notice that the new command bar is deleted.
 * 1) Click Close Preview to end the test.

<div class="references_section">