October 22, 2014
Hot Topics:
RSS RSS feed Download our iPhone app

Using Visual Studio to Write Word Add-ins

  • August 4, 2009
  • By Jani Järvinen
  • Send Email »
  • More Articles »

Task panels as user controls

To create a new custom task panel for Word, you need to add a Windows Forms user control to your project. To do this, open the Add New Item dialog box and select the User Control template from the Windows Forms group (Figure 6). Alternatively, you can use the Project menu's "Add User Control" command.



Click here for larger image

Figure 6. Custom task panels are implemented as WinForms user controls.

Once added, the user control will show as a blank, gray area in the Visual Studio designer. The next step would be to add controls to the designer surface. You will also need a small piece of code in the ThisAddIn.cs file to register your task panel with Word, and make it visible. The code is similar to the following:

  SalesToolsUserControl userControl =
    new SalesToolsUserControl();
  CustomTaskPane myCustomTaskPane =
    this.CustomTaskPanes.Add(
    userControl, "Sales Tools");
  myCustomTaskPane.Visible = true;

This code is added to the ThisAddIn_Startup method in the ThisAddIn.cs file. In the code, an instance of the user control (here called SalesToolsUserControl) is created, and then it is added to the list of custom task panes that Word controls. Finally, the pane is shown on the screen.

Implementing the functionality for the add-in

Once you have the basic user control skeleton created for your custom task pane, it is time to add some functionality. You can easily design the user interface of your pane in Visual Studio, as a full-blown form designer is already there. By default, Word sets the pane's width to equal 200 pixels, with a height dependent on the size of Word's main window. You might wish to set the width of your user control to equal 200 pixels so that designing would be easier.

Figure 7 shows the designed user interface for the sample user control. Overall, the user interface itself is very basic, but it's the underlying code that makes the add-in useful. The first feature in the add-in allows the user to type in a customer ID, and then the add-in will fetch that customer's details from the Northwind SQL Server sample database, and add them to the active Word document.


Figure 7. The sample application's task panel in Visual Studio designer.
The code to fetch the details is straightforward: an SQL connection is opened, a command is executed, and finally a SqlDataReader object is used to fetch the results of the query: string connStr = Properties.Settings.

      Default.DatabaseConnection;
  SqlConnection conn = new SqlConnection(
      connStr);
  try
  {
    conn.Open();
    string sql = "SELECT [companyname], "+
        "[contactname], [address], [city], " +
        "[region], [postalcode] "+
        "FROM [customers] " +
        "WHERE [customerid] = @custid";
    SqlCommand cmd = new SqlCommand(
        sql, conn);
    cmd.Parameters.AddWithValue(
        "@custid", customerId);
    try
    {
      SqlDataReader reader =
          cmd.ExecuteReader();
      try
      {
        if (reader.Read())
        {
          CustomerDetails cust =
              new CustomerDetails();
          cust.CompanyName = reader.GetString(0);
          cust.ContactName = reader.GetString(1);
          cust.Address = reader.GetString(2);
          cust.City = reader.GetString(3);
          if (!reader.IsDBNull(4))
          {
              cust.Region = reader.GetString(4);
          }
          cust.ZipCode = reader.GetString(5);
  
          // finished
          return cust;
        }
      }
  ...

Here, the connection string is read from the add-in's XML configuration file, and the given customer ID is passed as a parameter to the SqlCommand object. The results are returned in a custom class instance, which contains simple public properties for each value.

Once the query has been executed, it is time to insert the results into the active Word document.

This is done with the following code:

  CustomerDetails cust =
    DataAccess.GetCustomerDetails(
    customerIdTextBox.Text);
  // format text
  StringBuilder buffer = new StringBuilder();
  buffer.AppendLine(cust.CompanyName);
  buffer.AppendLine(cust.ContactName);
  buffer.AppendLine(cust.Address);
  buffer.AppendLine(cust.City);
  buffer.AppendLine(cust.Region);
  buffer.AppendLine(cust.ZipCode);
  // insert text at the current cursor location
  Microsoft.Office.Interop.Word.Application
    word = Globals.ThisAddIn.Application;
  Word.Range selection = word.Selection.Range;
  selection.Text = buffer.ToString();

The main interaction with Word happens in the last three lines of code. The Globals class is a designer-created class that is part of every Word add-in project, and is created automatically by Visual Studio when you start the project. It lives in the hidden ThisAddIn.Designer.cs file. Through the Globals object, you can access your add-in's ThisAddIn class. In turn, this class then contains the Application reference, which points to Word's automation interface master object. The Word object is defined in the Microsoft.Office.Interop.Word.Application namespace, which has a rather lengthy name to type. Thus, you might wish to use the following C# using statements to help you manage the long names:

  using Word = Microsoft.Office.Interop.Word;
  using Office = Microsoft.Office.Core;
  using Microsoft.Office.Tools.Word;
  using Microsoft.Office.Tools.Word.Extensions;
  using Microsoft.Office.Tools;

These same using statements are available in ThisAddIn.cs, from which you might wish to copy them to your user control file.





Page 2 of 4



Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Sitemap | Contact Us

Rocket Fuel