Previous Page
Next Page

Working with the ActionsPane Control

A first step to understanding how VSTO's ActionsPane control works is delving a little into the architecture of VSTO's ActionsPane support.

The ActionsPane Architecture

The Document Actions task pane is a window provided by Office that can host ActiveX controls, as shown in Figure 15-4. VSTO places a special invisible ActiveX control in the Document Actions task pane that in turn hosts a single Windows Forms UserControl. This UserControl is represented in the VSTO programming model by the ActionsPane controlaccessible in Word via Document.ActionsPane and accessible in Excel via Globals.ThisWorkbook.ActionsPane.

Figure 15-4. The four layers of the ActionsPane architecture.


Although the Document Actions task pane can host multiple ActiveX controls, VSTO only needs to put a single ActiveX control and a single UserControl in the Document Actions task pane window because the UserControl can host multiple Windows Forms controls via its Controls collection (ActionsPane.Controls). You can add Windows Forms controls to the ActionsPane by using the ActionsPane.Controls.Add method.

The UserControl placed in the ActionsPane window is set to expand to fit the area provided by the ActionsPane window. If the area of the Document Actions task pane is not big enough to display all the controls hosted by the UserControl, it is possible to scroll the UserControl by setting the AutoScroll property of ActionsPane to TRue.

The ActionsPane control is a wrapper around System.Windows.Forms.UserControl with most of the properties, methods, and events of a UserControl. It also adds some properties, events, and methods specific to ActionsPane. When you understand the architecture in Figure 15-4, you will not be too surprised to know that some properties from UserControl that are exposed by ActionsPane such as position-related properties, methods, and events do not do anything. For example, because the position of the ActionsPane UserControl is forced to fill the space provided by the ActionsPane window, you cannot reposition the UserControl to arbitrary positions within the Document Actions task pane window.

Adding Windows Forms Controls to the Actions Pane

The basic way you add your custom UI to the actions pane is by adding Windows Forms controls to the actions pane's Controls collection. Listing 15-1 illustrates this approach. It first declares and creates an instance of a System.Windows.Forms.Button control. This control is then added to the actions pane by calling the Add method of the Controls collection associated with the actions pane and passing the button instance as a parameter to the Add method.

The actions pane is smart about arranging controls within the ActionsPane. If multiple controls are added to the Controls collection, the actions pane can automatically stack and arrange the controls. The stacking order is controlled by the ActionsPane.StackOrder property, which is of type Microsoft.Office.Tools.StackStyle. It can be set to None for no automatic positioning or can be set to FromTop, FromBottom, FromLeft, or FromRight. Figure 15-5 shows the effect of the various StackOrder settings.

Figure 15-5. The result of changing the ActionsPane StackOrder setting from top left: None, FromLeft, FromBottom, FromTop, and FromRight.


Listing 15-3 shows some code that adds and positions controls in the actions pane when StackOrder is set to either StackStyle.FromBottom and automatically positioned or set to StackStyle.None and manually positioned.

Listing 15-3. A VSTO Excel Customization That Adds and Positions Controls with Either StackStyle.None or StackStyle.FromBottom
using System;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using Microsoft.VisualStudio.OfficeTools.Interop.Runtime;
using Excel = Microsoft.Office.Interop.Excel;
using Office = Microsoft.Office.Core;

namespace ExcelWorkbook1
{
  public partial class Sheet1
  {

    public Button button1 = new Button();
    public Button button2 = new Button();
    public Button button3 = new Button();

    private void Sheet1_Startup(object sender, EventArgs e)
    {
      button1.Text = "Button 1";
      button2.Text = "Button 2";
      button3.Text = "Button 3";

      Globals.ThisWorkbook.ActionsPane.BackColor = Color.Aquamarine;

      Globals.ThisWorkbook.ActionsPane.Controls.Add(button1);
      Globals.ThisWorkbook.ActionsPane.Controls.Add(button2);
      Globals.ThisWorkbook.ActionsPane.Controls.Add(button3);

      if (MessageBox.Show(
         "Do you want to auto-position the controls?",
         "StackStyle",
         MessageBoxButtons.YesNo) == DialogResult.Yes)
      {
        Globals.ThisWorkbook.ActionsPane.StackOrder =
          Microsoft.Office.Tools.ActionsPane.StackStyle.FromBottom;
      }
      else
      {
        Globals.ThisWorkbook.ActionsPane.StackOrder =
          Microsoft.Office.Tools.ActionsPane.StackStyle.None;
        button1.Left = 10;
        button2.Left = 20;
        button3.Left = 30;

        button1.Top = 0;
        button2.Top = 25;
        button3.Top = 50;
      }
    }

    #region VSTO Designer generated code
    private void InternalStartup()
    {
      this.Startup += new System.EventHandler(Sheet1_Startup);
    }
    #endregion
  }
}

Adding a Custom User Control to the Actions Pane

A more visual way of designing your application's actions pane UI is by creating a user control and adding that user control to the ActionsPane's control collection. Visual Studio provides a rich design-time experience for creating a user control. To add a user control to your application, click the project node in the Solution Explorer and choose Add User Control from Visual Studio's Project menu. Visual Studio will prompt you to give the User Control a filename such as UserControl1.cs. Then Visual Studio will display the design view shown in Figure 15-6.

Figure 15-6. The design view for creating a custom user control.


The design area for the user control has a drag handle in the lower-right corner that you can drag to change the size of the user control. Controls from the toolbox can be dragged onto the user control design surface and positioned as desired. Figure 15-7 shows a completed user control that uses check boxes, text boxes, and labels.

Figure 15-7. A custom user control.


Listing 15-4 shows a VSTO Excel customization that adds this custom user control to the Document Actions task pane. The user control created in Figure 15-7 is a class named UserControl1. Listing 15-4 creates an instance of UserControl1 and adds it to ActionPane's Controls collection using the Add method.

Listing 15-4. A VSTO Excel Customization That Adds a Custom User Control to the Task Pane
using System;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using Microsoft.VisualStudio.OfficeTools.Interop.Runtime;
using Excel = Microsoft.Office.Interop.Excel;
using Office = Microsoft.Office.Core;

namespace ExcelWorkbook1
{
  public partial class Sheet1
  {
    public UserControl1 myUserControl = new UserControl1();

    private void Sheet1_Startup(object sender, EventArgs e)
    {
      Globals.ThisWorkbook.ActionsPane.Controls.Add(myUserControl);
    }

    #region VSTO Designer generated code
    private void InternalStartup()
    {
      this.Startup += new EventHandler(Sheet1_Startup);
    }
    #endregion
  }
}

Figure 15-8 shows the resulting Document Actions task pane shown when Listing 15-4 is run.

Figure 15-8. The result of running Listing 15-4.


Contextually Changing the Actions Pane

A common application of the ActionsPane is providing commands in the Document Actions task pane that are appropriate to the context of the document. For example, in an order form application, the Document Actions task pane might display a button for selecting a known customer when filling out the customer information section of the document. When the user is filling out the order part of the document, the Document Actions task pane might display a button for examining available inventory.

Listing 15-5 shows a VSTO Excel customization where two named ranges have been defined. One called orderInfo is a range of cells where the contents of an order are placed. The other called customerInfo is a range of cells specifying the customer information for the customer placing the order. Listing 15-5 contextually adds and removes an inventoryButton when the orderInfo range is selected and a customerButton when the customerInfo range is selected or deselected. It does this by handling NamedRange.Selected and NamedRange.Deselected events. When the Selected event indicating the customerInfo range of cells is selected, Listing 15-5 adds a customerButton that when clicked would allow the user to pick an existing customer. Listing 15-5 removes the customerButton when the customerInfo.Deselected event is raised. It calls ActionsPane.Controls.Remove to remove the customerButton from the actions pane.

Listing 15-5 is written in a way so that if both the customerInfo range and the orderInfo range are selected at the same time, both the customerButton and the inventoryButton would be visible in the document task pane.

Listing 15-5. A VSTO Excel Customization That Changes the Actions Pane Based on the Selection
using System;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using Microsoft.VisualStudio.OfficeTools.Interop.Runtime;
using Excel = Microsoft.Office.Interop.Excel;
using Office = Microsoft.Office.Core;

namespace ExcelWorkbook1
{
  public partial class Sheet1
  {
    public Button customerButton = new Button();
    public Button inventoryButton = new Button();

    private void Sheet1_Startup(object sender, EventArgs e)
    {
      customerButton.Text = "Select a customer...";
      inventoryButton.Text = "Check inventory...";

      this.orderInfo.Selected +=
        new Excel.DocEvents_SelectionChangeEventHandler(
        OrderInfo_Selected);

      this.orderInfo.Deselected +=
        new Excel.DocEvents_SelectionChangeEventHandler(
        OrderInfo_Deselected);

      this.customerInfo.Selected +=
        new Excel.DocEvents_SelectionChangeEventHandler(
        CustomerInfo_Selected);

      this.customerInfo.Deselected +=
        new Excel.DocEvents_SelectionChangeEventHandler(
        CustomerInfo_Deselected);
    }

    #region VSTO Designer generated code
    private void InternalStartup()
    {
      this.Startup += new System.EventHandler(Sheet1_Startup);
    }
    #endregion

    void OrderInfo_Selected(Excel.Range target)
    {
      Globals.ThisWorkbook.ActionsPane.Controls.Add(inventoryButton);
    }

    void OrderInfo_Deselected(Excel.Range target)
    {
      Globals.ThisWorkbook.ActionsPane.Controls.Remove(inventoryButton);
    }

    void CustomerInfo_Selected(Excel.Range target)
    {
      Globals.ThisWorkbook.ActionsPane.Controls.Add(customerButton);
    }

    void CustomerInfo_Deselected(Excel.Range target)
    {
      Globals.ThisWorkbook.ActionsPane.Controls.Remove(customerButton);
    }
  }
}

You can also change the contents of the Document Actions task pane as the selection changes in a Word document. One approach is to use bookmarks and change the contents of the Document Actions task pane when a particular bookmark is selected. A second approach is to use the XML mapping features of Word and VSTO's XML-Node and XMLNodes controls described in Chapter 22, and change the contents of the Document Actions task pane when a particular XMLNode or XMLNodes is selected in the document.

Detecting the Orientation of the Actions Pane

In addition to the UserControl events documented in the .NET class libraries documentation, ActionsPane adds one additional event: OrientationChanged. This event is raised when the orientation of the actions pane is changed. The actions pane can be in either a horizontal or vertical orientation. Figure 15-3 shows an actions pane in a vertical orientation. Figure 15-9 shows a horizontal orientation.

Figure 15-9. The actions pane in a horizontal orientation.


Listing 15-6 shows a VSTO Excel customization that adds several buttons to the ActionsPane's Controls collection. Listing 15-6 also handles the OrientationChanged event and displays the orientation of the ActionsPane in a dialog. It determines the orientation of the actions pane by checking the ActionsPane.Orientation property. The Orientation property returns a member of the System.Windows.Forms.Orientation enumeration: either Orientation.Horizontal or Orientation.Vertical.

Listing 15-6. A VSTO Excel Customization That Handles ActionsPane's OrientationChanged Event
using System;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using Microsoft.VisualStudio.Tools.Applications.Runtime;
using Excel = Microsoft.Office.Interop.Excel;
using Office = Microsoft.Office.Core;

namespace ExcelWorkbook1
{
  public partial class Sheet1
  {
    public Button button1 = new Button();
    public Button button2 = new Button();
    public Button button3 = new Button();

    private void Sheet1_Startup(object sender, EventArgs e)
    {
      button1.Text = "Button 1";
      button2.Text = "Button 2";
      button3.Text = "Button 3";

      Globals.ThisWorkbook.ActionsPane.StackOrder =
        Microsoft.Office.Tools.StackStyle.FromTop;

      Globals.ThisWorkbook.ActionsPane.Controls.Add(button1);
      Globals.ThisWorkbook.ActionsPane.Controls.Add(button2);
      Globals.ThisWorkbook.ActionsPane.Controls.Add(button3);

      Globals.ThisWorkbook.ActionsPane.BackColor = Color.Aquamarine;

      Globals.ThisWorkbook.ActionsPane.OrientationChanged +=
        new EventHandler(ActionsPane_OrientationChanged);
    }

    void ActionsPane_OrientationChanged(object sender, EventArgs e)
    {
      Orientation orientation =
       Globals.ThisWorkbook.ActionsPane.Orientation;
      MessageBox.Show(String.Format(
        "Orientation is {0}.", orientation.ToString()));
    }

    #region VSTO Designer generated code
    private void InternalStartup()
    {
      this.Startup += new System.EventHandler(Sheet1_Startup);
    }
    #endregion
  }
}

Scrolling the Actions Pane

The AutoScroll property of the ActionPane gets or sets a bool value indicating whether the actions pane should display a scroll bar when the size of the Document Actions task pane is such that not all the controls can be shown. The default value of AutoScroll is true. Figure 15-10 shows a Document Actions task pane with 10 buttons added to it. Because AutoScroll is set to true, a scroll bar is shown when not all 10 buttons can be displayed given the size of the Document Actions task pane.

Figure 15-10. The actions pane when AutoScroll is set to true.


Showing and Hiding the Actions Pane

The actions pane is automatically shown when you add controls to ActionsPane's Controls collection using the Add method. To show and hide the actions pane programmatically, you need to use the Excel or Word object model. In Excel, set the Application.DisplayDocumentActionTaskPane property to TRue or false. In Word, set the property Application.TaskPanes[WdTaskPanes.wdTaskPaneDocument-Actions].Visible property to TRue or false.

You might be tempted to call ActionsPane.Hide or set ActionsPane.Visible to false to hide the ActionsPane. These approaches do not work because you are actually hiding the UserControl shown in Figure 15-4 that is hosted by the Document Actions task pane rather than just the Document Actions task pane. You should use the object model of Excel and Word to show and hide the actions pane.

Listing 15-7 shows a VSTO Excel customization that shows and hides the actions pane on the BeforeDoubleClick event of the Worksheet by toggling the state of the Application.DisplayDocumentActionTaskPane property. Note that the DisplayDocumentActionTaskPane property is an application-level property that is only applicable when the active document has a Document Actions task pane associated with it. If the active document does not have a Document Actions task pane associated with it, accessing the DisplayDocumentActionTaskPane property will raise an exception.

Listing 15-7. A VSTO Excel Customization That Shows and Hides the Actions Pane When Handling the BeforeDoubleClick Event
using System;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using Microsoft.VisualStudio.OfficeTools.Interop.Runtime;
using Excel = Microsoft.Office.Interop.Excel;
using Office = Microsoft.Office.Core;

namespace ExcelWorkbook1
{
  public partial class Sheet1
  {
    bool visible = true;

    private void Sheet1_Startup(object sender, System.EventArgs e)
    {
      for (int i = 1; i < 11; i++)
      {
        Button myButton = new Button();
        myButton.Text = String.Format("Button {0}", i);
        Globals.ThisWorkbook.ActionsPane.Controls.Add(myButton);
      }

      this.BeforeDoubleClick +=
        new Excel.DocEvents_BeforeDoubleClickEventHandler(
        Sheet1_BeforeDoubleClick);
    }

    #region VSTO Designer generated code
    private void InternalStartup()
    {
      this.Startup += new EventHandler(Sheet1_Startup);
    }
    #endregion

    void Sheet1_BeforeDoubleClick(Excel.Range target,
      ref bool cancel)
    {
      // Toggle the visibility of the ActionsPane on double-click.
      visible = !visible;
      this.Application.DisplayDocumentActionTaskPane = visible;
    }
  }
}

Listing 15-8 shows a VSTO Word application that shows and hides the actions pane on the BeforeDoubleClick event of the Document by toggling the state of the Application.TaskPanes[WdTaskPanes.wdTaskPaneDocumentActions].Visible property.

Listing 15-8. VSTO Word Customization That Shows and Hides the Actions Pane in the BeforeDoubleClick Event Handler
using System;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using Microsoft.VisualStudio.OfficeTools.Interop.Runtime;
using Word = Microsoft.Office.Interop.Word;
using Office = Microsoft.Office.Core;

namespace WordDocument1
{
  public partial class ThisDocument
  {

    private void ThisDocument_Startup(object sender, EventArgs e)
    {
      for (int i = 1; i < 11; i++)
      {
        Button myButton = new Button();
        myButton.Text = String.Format("Button {0}", i);
        ActionsPane.Controls.Add(myButton);
      }

      this.BeforeDoubleClick +=
        new Word.ClickEventHandler(
        ThisDocument_BeforeDoubleClick);
    }

    #region VSTO Designer generated code
    private void InternalStartup()
    {
      this.Startup += new EventHandler(ThisDocument_Startup);
    }
    #endregion

    void ThisDocument_BeforeDoubleClick(object sender,
      Word.ClickEventArgs e)
    {
      if (this.Application.TaskPanes[
        Word.WdTaskPanes.wdTaskPaneDocumentActions
        ].Visible == true)
      {
        this.Application.TaskPanes[
          Word.WdTaskPanes.wdTaskPaneDocumentActions
          ].Visible = false;
      }
      else
      {
        this.Application.TaskPanes[
          Word.WdTaskPanes.wdTaskPaneDocumentActions
          ].Visible = true;
      }
    }
  }
}

Attaching and Detaching the Actions Pane

Sometimes you will want to go beyond just hiding the actions pane and actually detach the actions pane from the document or workbook. You might also want to control whether the user of your document is allowed to detach the actions pane from the document or workbook. Recall from earlier in this chapter that the actions pane is actually a smart document solution, and as such it can be attached or detached from the document or workbook via Excel and Word's built-in dialogs for managing attached smart document solutions.

When the actions pane is detached from the document, this means that the Document Actions task pane will not be in the list of available task panes when the user drops down the list of available task panes, as shown in Figure 15-2. To programmatically detach the actions pane from the document, call the ActionsPane.Clear method. Doing so detaches the actions pane solution from the document and hides the Document Actions pane. Calling ActionsPane.Show reattaches the actions pane and makes it available again in the list of available task panes. Note that in Word, when you call ActionsPane.Clear, you must follow the call with a second call to the Word object model: Document.XMLReferences["ActionsPane"].Delete.

If you want to allow the user of your document to detach the actions pane solution by using the Templates and Add-ins dialog in Word shown in Figure 15-11 or the XML Expansion Packs dialog in Excel shown in Figure 15-12, you must set the ActionsPane.AutoRecover property to false. By default, this property is set to TRue, which means that even when the user tries to detach the actions pane solution by deselecting it in these dialogs, VSTO will recover and automatically reattach the actions pane solution.

Figure 15-11. The actions pane solution attached to a Word document is visible in Word's Templates and Add-Ins dialog and can be removed if ActionsPane.AutoRecover is not set to true.


Figure 15-12. The actions pane solution attached to an Excel workbook is visible in Excel's XML Expansion Packs dialog and can be removed if ActionsPane.AutoRecover is not set to true.


After an actions pane solution is attached to the document and the user saves the document, the next time the user opens the document, the actions pane will be available and can be selected at any time during the session. If your code does not add controls to the actions pane until some time after startup, you might want to call the ActionsPane.Clear method in the Startup handler of your VSTO customization to prevent the user from showing the actions pane before your VSTO customization has added controls to the ActionsPane control.

Some Methods and Properties to Avoid

As mentioned earlier, the ActionsPane is a user control that has a fixed location and size that is controlled by VSTO. As such, you should avoid using a number of position-related properties and methods on the ActionsPane control, as listed in Table 15-1.

Table 15-1. Methods and Properties of ActionsPane to Avoid

Left

Top

Width

Height

Right

Location

Margin

MaximumSize

MinimumSize

Size

TabIndex

AutoScrollMargin

AutoScrollMinSIze



Previous Page
Next Page