My vsto path (3): basic word knowledge

Source: Internet
Author: User
Tags printable characters

In the previous articleArticle, I initially introduced how to develop a vstoProgramIn this article, I will further introduce the development of the word plug-in. Word is a document tool that everyone has been familiar with in their daily work. It is also one of Microsoft's most profitable products. From the original word 1.0 to the present word 2010, after 13 generations of evolution, it has become a complicated system. (Here, let's just skip the question. The Code of office 2010 is version 14, but why do I say that word has evolved 13 generations in total? Because the Office does not have version 13, and the previous generation of Office 2007 is version 12, Microsoft thinks that the death number 13 is unlucky, so it skipped it directly ...... Oh my god ). Back to the truth, I recorded a video to demonstrate what I want to introduce.

This video describes a simple word search plug-in that includes the following features:

    1. Custom RIBBON
    2. Custom task pane
    3. Get the full text of word in vsto plug-in
    4. Modify the word content and style

Here, I have introduced how to create ribbon and task pane in the previous article. If you are not familiar with it, read it here.

 

Introduction to word Object Model

First of all, to develop a good program, we need to understand our development platform, and word itself is a very review platform. Here I will first introduce the object model of word. The word object model contains hundreds of different types of objects. The most important and common objects are application, document, range, selection, and bookmark. Their relationships are as follows:

Let me introduce these objects in sequence:

Application Object

An application represents a Word program, and a word program can contain multiple Word documents. In general, no matter how many Word documents you open, they are managed in a word process. The Excel files we will talk about later are different. At the same time, the application is the root of all word objects. You can use the application object to obtain other objects. During the development of addin, we can obtain the application object in the following ways:

 
Globals. thisaddin. Application
Document Object

The document object represents a Word document. Even if you open your word, it is an empty new document, and there will be a document. During development, the following attributes obtain the current document object from the application:

 
Globals. thisaddin. application. activedocument

In addition, the application object also maintains a set, namely application. Documents, which contains all open Word documents.

 

Range object

Range is a special object (I don't know how to translate this word properly in Chinese). In your daily use of word, you may not even know that such an object exists, but if you want to modify the content of the word body in program mode, range is a key object. In Microsoft's official statement, range represents a continuous area in the Document. Microsoft lists several features for it:

    1. The composition of range can be a separate insertion point, or a text range or the entire document.
    2. Range contains non-printable characters, such as spaces, tabs, and paragraph tags.
    3. Range can be the region of the selected content or the area outside the selected content.
    4. Range is invisible in the document, unlike the selected content that is always visible.
    5. Range does not save as a document. It only exists inCodeDuring running.

I will add 2 more

    1. Range has a definite start and end, but different ranges can have an intersection.
    2. The length of a range is changing. If you insert a word into a range, its length will automatically become longer.

There are many ways to get the range object. We can create a custom range through the range (ref object start = type. Missing, ref object end = type. Missing) method of the Document Object. All objects related to documents in Word have a range attribute, such as paragraph. Range and selection. range.

 

Selection object

Selection indicates the object selected by the current cursor. this object will be used with application. windowselectionchange during development.

 
1://
 
2:// Summary:
3:// Occurs when the selection changes in the active document window.
 
4:EventApplicationevents4_windowselectionchangeeventhandler windowselectionchange;

Delegate Interface

 
1:[Typelibtype (16)]
 
2:[Comvisible (False)]
 
3:Public Delegate VoidApplicationevents4_windowselectionchangeeventhandler (selection SEL );

 

Bookmark and Content Control

Bookmark is a bookmarks. It can be easily viewed by marking a Word document. During the development process, we can create a bookmark Based on range. For example:

 
1:// Mark the first document as a bookmark
2:Word. Range = globals. thisaddin. application. activedocument. Paragraphs [0]. range;
 
3:Range. bookmarks. Add ("Justintest");

 

Now we have introduced five main objects in word. Now we use what we have learned to implement the plug-in the starting video.

 

Plug-in: Custom Search panel

First, Let's define the function points we want to implement, get the content of the Word document, get the context related to the search keyword, and display it in listview. When the user clicks the project in listview, highlight the corresponding content in the Word document. The following describes how to implement these functions.

 

Obtain the full text of Word

To obtain the full text of the current word, we mainly need to solve two problems.

    1. How to obtain the current document object?
    2. How to obtain the document content through the document object?

For the first question, because the search function is mainly written in the usercontrol in task pane (this has been described in the previous article), the main method for getting the Document Object is as follows, is to get the activedocument object through the Application object, that is, the currently edited document:

 
Globals. thisaddin. application. activedocument

For the second problem, we have two methods: first, the document object has a paragraphs set, which contains the objects of each paragraph, and each paragraph object has a range attribute, we can use paragraph. range. text to obtain the body of each paragraph. Secondly, the document object has a range method, through which we can take the entire document as a range.

 

Search button code

 
1:Private VoidBtnsearch_click (ObjectSender, eventargs E)
 
2:{
 
3:// Clear the highlighted content in the document
 
4:Clearmark ();
 
5: 
 
6:Lvsearchresult. Items. Clear ();
 
7:If(String. Isnullorwhitespace (tbsearchtext. Text ))
 
8:{
9:Return;
 
10:}
 
11: 
 
12:// Search by paragraph
 
13:Word. Document currentdocument = globals. thisaddin. application. activedocument;
 
14:If(Currentdocument. Paragraphs! =Null&&
 
15:Currentdocument. Paragraphs. Count! = 0)
 
16:{
17:Foreach(Word. Paragraph paragraphInCurrentdocument. Paragraphs)
 
18:{
 
19:Matchcollection MC = RegEx. Matches (paragraph. range. Text, tbsearchtext. Text. Trim (), regexoptions. ignorecase );
 
20:If(MC. Count> 0)
 
21:{
 
22:Foreach(Match mInMC)
 
23:{
24:Try
 
25:{
 
26:IntStartindex = paragraph. range. Start + M. index;
 
27:IntEndindex = paragraph. range. Start + M. index + M. length;
 
28: 
 
29:Word. Range keywordrange = currentdocument. Range (startindex, endindex );
 
30:
31:// Obtain the context information
 
32:// Obtain the position of the first two words (if any)
 
33:Startindex = getstartpositionforview (paragraph, M, startindex );
 
34: 
 
35:// Obtain the location of the last two words (if any)
 
36:Endindex = getendpositionforview (paragraph, M, endindex );
 
37: 
38:// Display the search keyword and context in listview
 
39:Word. Range = currentdocument. Range (startindex, endindex );
 
40:Listviewitem item =NewListviewitem (range. Text );
 
41:Item. Tag = keywordrange;
 
42:Lvsearchresult. Items. Add (item );
 
43:}
 
44:Catch(Exception ex)
45:{
 
46:MessageBox. Show (ex. Message );
 
47:}
 
48:}
 
49:}
 
50:}
 
51:}
 
52:}

This section describes several functions of the Code:

    1. When the search function starts, clear the highlighted display in the document (the clearmark method will be introduced later ).
    2. Split into paragraphs and search for keywords in sequence.
    3. Obtain the context of the keyword and display it in listview. Note that, in the tag object of listviewitem, I saved the keyword range in the document to the listview click event.

 

Listview Click Event

1:Private VoidLvsearchresult_itemselectionchanged (ObjectSender, listviewitemselectionchangedeventargs E)
 
2:{
 
3:Clearmark ();
 
4:If(Lvsearchresult. selecteditems. Count> 0)
 
5:{
 
6:Word. Range = lvsearchresult. selecteditems [0]. TagAsWord. range;
 
7: 
8:// In order to restore the modified range, I first put the range and the original color into the class member.
 
9:_ Lastrange = range;
 
10:_ Lastrangebackcolor = range. highlightcolorindex;
 
11:Range. highlightcolorindex = word. wdcolorindex. wdyellow;
 
12:}
 
13:}

In general, this code is very simple. I will introduce the use of the range object a little. Here I modified the highlightcolorindex attribute to modify the background color of the text. If you modify the style related to the font, you can use range. font attribute. (In addition, I will introduce how to add hyperlinks, bookmarks, or content control through range in the next article ).

 

Other methods

1:Private VoidClearmark ()
 
2:{
 
3:If(_ Lastrange! =Null)
 
4:{
 
5:_ Lastrange. highlightcolorindex = _ lastrangebackcolor;
 
6:}
 
7:}

I will call this method in both the search event and the listview clicking method. It will use the range and color saved in lvsearchresult_itemselectionchanged to restore the previous style.

 

Summary

In this article, I introduced the basic content of the word object model and a word plug-in that I wrote, including operations on the application, document, and range objects. The word program contains a lot of content. I wanted to write the word knowledge I knew once, but I found that I have already written a lot here, so I am afraid everyone will be tired of reading it, so I will first introduce the development of the word plug-in the next article. Next content forecast:

    1. Modify context menu
    2. Insert content into the document
    3. Add hyperlinks and bookmarks
    4. Displays the Floating Box Based on the selected content.

 

Finally, the sample code in this article can be downloaded here. In addition, this article is welcome to reprint, but please keep the source, if you have any questions, you can contact me justin.tyrael@gmail.com.

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.