My path to the VSTO (iii): Word basics

Source: Internet
Author: User

Original: My path to VSTO (iii): Word basics

In the previous article, I initially covered how to develop a VSTO program, and in this article I'll go further into Word's plug-in development. Word is a document tool that everyone has been in touch with in their daily work and is one of Microsoft's most lucrative products. Word 2010, from the initial Word 1.0 to the present, has evolved over 13 generations and has become a more complex system. (Here's a little bit of a digression, version 14 for Office 2010, but why did I say that word evolved for 13 generations?) Because Office does not have version 13, the previous generation of Office 2007 is version 12, and Microsoft feels that 13 of this dead number is unlucky, so skip directly ... Oh my God). I've recorded a video to illustrate what this article is about.

This video describes a simple word search plugin that contains the following feature points

    1. Customizing the Ribbon
    2. customizing Task Pane
    3. Get Word content full text in VSTO plugin
    4. Modify Word content and styles

One of the things I've described in the previous article about how to create the Ribbon and task pane, if you're not familiar with it, can look here.

Word Object Model Introduction

First of all, to develop a good program, we need to understand our development platform, and word itself is a very review of the platform, I am here first from the Word object model to introduce. The Word object model contains a total of hundreds of different types of objects, the most critical of which is the application, Document, Range, Selection, and bookmark, and their relationships are as follows:

Let me introduce these objects in turn:

Application Object

Application represents a Word program, and a Word program can contain multiple Word documents. In popular words, no matter how many Word documents you open, it is managed within a word process. This is not the same as the Excel we will talk about later. While application is also the root of all Word objects, you can get other objects by application objects. During the addin development process, we can obtain the Application object in the following ways:

Globals.ThisAddIn.Application
Document Object

The Document object represents a Word document that, even if you just opened your word, is an empty new document. During the development process, the following property obtains the current document object from application:

    Globals.ThisAddIn.Application.ActiveDocument

In addition, the Application object maintains a collection, application.documents, with all of the open Word documents now in the pack.

Range Object

Range is a special object (I don't really know how to translate the word properly in Chinese), and you may not even know that there is such an object in your daily use of Word, but if you want to modify the contents of the word body programmatically, Range is a very critical object. Using Microsoft's official statement, range represents a contiguous area of the document, and Microsoft has listed several features for it:

    1. The component of range can be a separate insertion point, or it can be a text range or an entire document.
    2. Range contains nonprinting characters, such as spaces, tabs, and paragraph marks.
    3. Range can be the range represented by the current selection, or it can represent an area outside the current selection.
    4. Range is not visible in a document, unlike a selection that is always seen.
    5. Range is not saved with the document, but only during code run time.

I'll add 2 more to it.

    1. Range has a definite start and end, but there can be an intersection between the different range
    2. The length of range is variable, and if you insert a word into a range, its length will automatically grow.

There are many ways to get a Range object, and we can create a custom range by using the range of the Document object (ref objects Start = Type.Missing, ref object End = Type.Missing). Objects related to documents in Word have a Range property, such as Paragraph.range, Selection.Range.

Selection Object

Selection represents the object currently selected by the cursor and is used in conjunction with Application.windowselectionchange during the development process.

   1:          //
   2:          //Summary:
   3:          //     occurs when the selection changes in the active document window.
   4:          event Applicationevents4_windowselectionchangeeventhandler WindowSelectionChange;

Delegate interface

   1:      [TypeLibType (16)]
   2:      [ComVisible (false)]
   3:  public    delegatevoid applicationevents4_ Windowselectionchangeeventhandler (Selection Sel);

Bookmark and Content Control

Bookmark is bookmarks, make a mark in Word document, easy to consult. During the development process, we can create a bookmark based on range. Such as:

   1:      
   2:      word.range Range = globals.thisaddin.application.activedocument.paragraphs[0]. Range;
   3:      range. Bookmarks.add ("justintest");

Now that we've covered the main 5 objects in Word, we're using what we've learned to actually start the plugin in the video.

Plugins: Customizing the search panel

I'll define the function point we want to implement, get the Word document content, get the context associated with retrieving the keyword and display it in the ListView, highlighting the corresponding content in the Word document when the user points to the item in the ListView. The following is an introduction to how to implement these features.

get the full text of Word
To get the full text of the current word, we mainly solve two problems.

    1. How do I get the current document object?
    2. How do I get the contents of a document through the Documents object?

For the first question, because the search function is primarily written in UserControl in Task pane (which has been described in the previous article), the main method of obtaining the Document object is Is the object that gets activedocument through the Application object, the document that is currently being edited:

    Globals.ThisAddIn.Application.ActiveDocument

For the second question, we have two methods: first, the Document object has a paragraphs collection, which contains the objects for each paragraph, and each paragraph object has a Range property, We can get the body of each paragraph by Paragraph.Range.Text. Second, the document object has a range method through which we can use the entire document as a range.

Search Button Code

   1:          privatevoid btnSearch_Click (object sender, EventArgs e)
   2:          {
   3:              //clear highlighting in the document
   4:              Clearmark ();
   5:  
   6:              lvSearchResult.Items.Clear ();
   7:              if (string. Isnullorwhitespace (Tbsearchtext.text))
   8:              {
   9:                  return;
  Ten:              }
One   :  
Page   :              //Search by paragraph
  :              word.document currentdocument = Globals.ThisAddIn.Application.ActiveDocument;
+   :              ifnull &&
  :                  CurrentDocument.Paragraphs.Count! = 0)
  :              {
  :                  foreach in currentdocument.paragraphs)
  :                  {
  :                      MatchCollection mc = regex.matches (paragraph. Range.Text, TbSearchText.Text.Trim (), regexoptions.ignorecase);
  :                      if (MC. Count > 0)
  :                      {
  :                          foreach in MC)
  :                          {
  :                              try
  :                              {
  :                                  int StartIndex = paragraph. Range.Start + M.index;
Int.   :                                  int EndIndex = paragraph. Range.Start + M.index + m.length;
  :  
  £ º                                  word.range keywordrange = Currentdocument.range (StartIndex, EndIndex);
  30:                                  
  :                                  //Get contextual information
+   :                                  //Get the position of the first two words (if any)
  :                                  startIndex = Getstartpositionforview (paragraph, m, StartIndex);
  :  
  :                                  //Get the position of the following two words (if any)
  :                                  endIndex = Getendpositionforview (paragraph, m, EndIndex);
  Panax Notoginseng  :
  :                                  //Display the retrieved keyword and its context in the ListView
In   :                                  Word.Range Range = Currentdocument.range (StartIndex, EndIndex);
Max   :                                  new ListViewItem (range. Text);
In   :                                  item. Tag = Keywordrange;
  :                                  lvSearchResult.Items.Add (item);
  :                              }
  :                              catch (Exception ex)
  :                              {
  :                                  MessageBox.Show (ex. Message);
  :                              }
  :                          }
  :                      }
  :                  }
  Wuyi:              }
  :          }

Describe some of the functional points of this code:

    1. When the search feature starts, clear the highlighting in the document (the Clearmark method is described later).
    2. Sub-paragraphs and find keywords in turn.
    3. Gets the context of the keyword and puts it in the ListView display. When I need to be aware, I am in the tag object of ListViewItem, I have deposited the range of keyword in the document for the ListView click event.

ListView Click event

   1:          privatevoid lvsearchresult_itemselectionchanged (object sender, Listviewitemselectionchangedeventargs e)
   2:          {
   3:              Clearmark ();
   4:              if (LvSearchResult.SelectedItems.Count > 0)
   5:              {
   6:  as                 Word.Range;
   7:  
   8:                  //In order to recover the modified range, I first put the range and the original color into the members of class
   9:                  _lastrange = range;
  Ten:                  _lastrangebackcolor = range. HighlightColorIndex;
One   :                  range. HighlightColorIndex = Word.WdColorIndex.wdYellow;
  :              }
  :          }

Overall this code is very simple, I slightly introduce the use of the Range object, here I modified the HighlightColorIndex property, to modify the background color of the text, if you modify the font-related style, you can pass the Range.font property. (In addition, I'll show you how to use range to add hyperlinks, bookmarks, or content Control in the next article).

Other methods

   1:          privatevoid Clearmark ()
   2:          {
   3:              ifnull)
   4:              {
   5:                  _lastrange.highlightcolorindex = _lastrangebackcolor;
   6:              }
   7:          }

I call this method in both the search event and the ListView click Method, which uses the range and color saved in lvsearchresult_itemselectionchanged to restore the previous style.

Summarize

In this article, I covered the basic content of the Word object model and a word plugin I wrote that contained operations on application, document, and Range objects. Word program contains a lot of content, originally want to understand the word knowledge of a write, but wrote here to find already wrote a lot of, afraid everyone will see tired, so first sent out, and then next article, I will further introduce word plug-in development. Next Content preview:

    1. Modify the right-click menu
    2. Inserting content into a document
    3. Add hyperlinks, bookmarks
    4. Displays a hover box based on the selection

Finally, the code for this example can be downloaded here. In addition, this article welcome reprint, but please keep the source, if you have any questions, you can contact me [email protected].

My path to the VSTO (iii): Word basics

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.