Visual studio 2010 word

      Данная инструкция поможет вам начать работать с шаблонами Microsoft Word. Для начала работы вам понадобится компьютер с установленным на нем пакетом Microsoft Office. В данном случае используется профессиональная версия 2010 года. В Microsoft Word 2010 можно создать шаблон, сохраняя документ как DOTX-файл, DOT-файл или DOTM-файл (файл типа DOTM позволяет разрешить макросы в файле).
      Шаблон — это тип документа, при открытии которого создается его копия. Например, бизнес-план — распространенный документ, часто создаваемый в Word. Вместо создания структуры бизнес-плана с самого начала можно использовать шаблон со стандартным макетом страницы, шрифтами, полями и стилями. Остается лишь открыть шаблон и заполнить документ соответствующим текстом и данными. При сохранении в виде файла .docx или .docm документ сохраняется отдельно от шаблона, на котором он основан.
      В шаблоне можно сохранить рекомендуемые разделы или обязательный текст, а также элементы управления содержимым, такие как стандартный раскрывающийся список или специальная эмблема. Можно добавить защиту для раздела шаблона или применить к шаблону пароль, защищающий содержимое шаблона от изменений.

      Начать можно с пустого документа и сохранить его как шаблон или создать шаблон на основе существующего документа или шаблона. Запустите Microsoft Word, перейдите во вкладку «Файл» и выберете пункт «Создать». Шаблоны Word для большинства видов документов можно найти на веб-сайте Office.com. В данном разделе вам предлагается выбрать готовые шаблоны или создать собственный. Выберете кнопку «Мои шаблоны».

      В открывшемся окне, вам предложено создать новый документ, но стоит задача создать шаблон. Для этого найдите внизу окна пункт «Создать» и выберете «шаблон».

Теперь необходимо сохранить шаблон. Перейдите во вкладку «Файл» и выберете пункт «Сохранить как».

      В открывшемся окне выберете директорию для сохранения, а тип файла поставьте «Шаблон Word 97-2003 (*.dot)». Данный формат позволит вам использовать шаблон как со старым офисом, версии 2003, так и с новыми версиями. Имя файла оставьте по умолчанию.

      После того как вы сохранили шаблон, для добавления элементов управления содержимым необходимо отобразить вкладку «Разработчик». Перейдите «Файл»-«Параметры».

      Откройте вкладку «Настройка ленты», в правой части окна, в списке «Настройка ленты» выберите пункт «Основные вкладки». Установите в списке флажок Разработчик и нажмите кнопку ОК.

После закрытия окна «Параметры Word», вы увидите дополнительную вкладку «Разработчик».

На вкладке «Разработчик» в группе «Элементы управления» нажмите кнопку «Режим конструктора».

      Добавим к шаблону стандартные блоки. Стандартные блоки — это многократно используемые элементы содержимого или другие части документа, которые хранятся в коллекциях и в любое время доступны для повторного использования. Стандартные блоки также можно хранить и распространять с помощью шаблонов. Так как мы сохранили шаблон в старом формате 97-2003, вам будут доступны только формы предыдущих версий. В группе «Элементы управления», найдите и нажмите кнопку «Инструменты из предыдущих версий». В выпадающем меню вам будет предложен ряд блоков, доступных для вашего шаблона.

Добавьте несколько блоков, например элемент управления формы – поле, флажок, надпись.

После добавления, у вас получится вот такой вариант.

      Для того чтобы мы могли обращаться к этим элементам, необходимо задать каждому уникальную закладку. Для этого выберете добавленный элемент – поле, сделайте клик правой клавишей мыши по нему и выберете из контекстного меню, пункт «Свойства».

      Найдите внизу окна, поле «закладка» и введите новое уникальное имя, по которому вы будете обращаться к элементу. В нашем случае для исключения ошибок с закладками на русском, введите на английской раскладке, имя: T1, т.е сокращенно текстовое поле №1. Нажмите ОК.

      Сохраните и закройте шаблон. Откройте Microsoft Visual Studio. В данной инструкции будет использована версия 2010. Создайте новый проект Windows Form. Добавим пространство имен Microsoft.Office.Interop.Word, необходимое нам для работы. Нажмите на клавиатуре клавишу F7, для перехода в листинг формы. В самом начале листинга, где объявляются пространства имен необходимые для работы проекта, добавьте еще одно:

using Word = Microsoft.Office.Interop.Word;

      Далее необходимо добавить ссылку на библиотеку добавленного пространства имен, в наше решение. Для этого перейдите в «Обозреватель решений», откройте вкладку «Ссылки» и сделайте по ней клик правой клавишей мыши, в открывшемся контекстном меню, выберете пункт «Добавить ссылку…».

      После открытия окна «Добавить ссылку», перейдите во вкладку «.Net» и найдите необходимый нам компонент Microsoft.Office.Interop.Word версии 12.0.0.0 и нажмите кнопку ОК.

      После добавления ссылки на данную библиотеку, вы увидите ее название в обозревателе решений, в подразделе «Ссылки».

Поместите на форму два компонента, TextBox и Button:

      Перейдите в конструктор формы и сделайте двойной клик по компоненту, вы перейдете в автоматически созданный метод button1_Click. Добавьте следующий код:

Word._Document oDoc = GetDoc(Environment.CurrentDirectory + "\Dot1.dot"); //Указываем путь к шаблону
oDoc.SaveAs(FileName: Environment.CurrentDirectory + "\For_print.doc");   //Путь к заполненному шаблону
oDoc.Close();

      Класс Environment.CurrentDirectory возвращает полный путь к текущей рабочей папке, к месту в котором расположен ваш скомпилированный проект. Скопируйте ваш шаблон в папку отладки вашего проекта по умолчанию это папка Visual Studio 2010ProjectsWindowsFormsWordDotWindowsFormsWordDotbinDebug. Так же добавьте дополнительно в листинг формы два метода:

Word._Application oWord = new Word.Application();
private Word._Document GetDoc(string path)
{
    Word._Document oDoc = oWord.Documents.Add(path);
    SetTemplate(oDoc);
    return oDoc;
}

private void SetTemplate(Word._Document oDoc)
{
    oDoc.Bookmarks["T1"].Range.Text = textBox1.Text;   
}

      Запустите приложение клавишей «F5» и введите в текстовое поле текст, который будет вставлен ив шаблон.

      После ввода текста, нажмите на кнопку «Button1» вашей формы. Перейдите в директорию расположения вашего приложения и откройте, созданный вашим приложением по шаблону текстовый документ «For_print.doc».

      Дальше по такому же принципу, вы можете нарисовать таблицу и с помощью этой инструкции ее заполнить. Для примера, это может выглядеть так:

[Update: The source code has been updated to Visual Studio 2017 and DocumentFormat.OpenXml 2.8.1. You can download the code from GitHub.]

This utility generates Word documents from templates using Content controls. The utility source code is available for download at http://worddocgenerator.codeplex.com/. It has been created in Visual Studio 2010 and uses Open Xml 2.0 SDK which can be downloaded from http://www.microsoft.com/download/en/details.aspx?id=5124.

The next parts in this series are

  • In Part 2 I have discussed about
    • List of functionalities that can be achieved using the utility/source code
    • Description regarding Samples provided with utility
    • New samples added in this update
  • In Part 3 I have explained one of the way to “Refresh the document from within the document(e.g. right click on document and click Refresh) using document-level projects for Word 2007 and Word 2010“

The purpose of creating this utility was to use the Open Xml 2.0 SDK to generate Word documents based on predefined templates using minimum code changes. These documents can either be refreshable or non- refreshable. I’ll explain this difference later. Also there is no dependency that Word should be installed.

A few samples for generating Word 2010 documents have been provided. The screenshots below display the sample template and the document generated out of this template using this utility.

Word 2010 Template –> Generated Document:

3

Word 2010 Template –> Generated Document –> Refreshed Document:

1

Document Refresh from within Word –> Refreshed Document:

2

Template Design:

The sample templates are inside “WordDocumentGenerator.ClientSample Templates” folder. A content control as displayed below can have Title and Tag properties.

clip_image003

The logic is to have a tag property of a content control and then populate data using that placeholder. This means every content control inside a Word template will have a different Tag.

As per image above the tag of the content control is “PlaceholderNonRecursiveB”. During document generation we can assign (not mandatory) a unique Id e.g. Guid of a record to make the tag unique e.g. “PlaceholderNonRecursiveB:Guid”. Let’s say that we have an Id and Name field. Thus the Name will be the content of the control and tag will be “PlaceholderNonRecursiveB:Id”. As per Word 2010 the Tag maximum length is 64.

In code we map the tag to the PlaceHolderType enum.

public enum PlaceHolderType
{
        None = 0,
        Recursive = 1,
        NonRecursive = 2,
        Ignore = 3,
        Container = 4
}
There can be multiple types of PlaceHolders
  • Recursive: This type corresponds to controls where there is 1:N relation between template and data i.e. one example will be repeating a list of Items.
  • Non-Recursive: This type corresponds to controls where there is 1:1 relation between template and data i.e. one example will be showing a User name.
  • Ignore: No action is required for these controls.
  • Container: This type is required only for refreshable documents. We save the container region in CustomXmlPart the first time document is generated from template. Next time onwards we retrieve the container region that was saved and refresh the document. This makes the document self-refreshable.

I’ve named the tags in “Test_Template – 1.docx” as per their PlaceHolder type to make it more clear.

Implementation:

As explained above the Tag property will used to bind data to this content control. The project “WordDocumentGenerator.Library” is the utility library. The project “WordDocumentGenerator.Client” shows how this library can be used to generate documents.

“DocumentGenerator” is the base class that needs to be inherited by the document generators. The sample generators location is “WordDocumentGenerator.ClientSample Document Generators”.

In order to protect the document I’ve used already created salt and hash. For an implementation where one needs to have document protection enabled for custom passwords one can view http://blogs.msdn.com/b/vsod/archive/2010/04/05/how-to-set-the-editing-restrictions-in-word-using-open-xml-sdk-2-0.aspx

Summary:

The purpose of creating this utility was to use the Open Xml 2.0 SDK to generate Word documents based on predefined templates using minimum code changes. These documents can either be refreshable or non- refreshable. New samples will be added as per feedback.

Table of Contents

  • Introduction
  • Building the Sample

You can download the source code from this link Source
Code Link

Introduction

The main purpose of this article is to explain how to create simple Excel and Microsoft Word Add-Ins using Visual
Studio Tools for Office
 (VSTO).
VSTO is available as an add-in tool with Microsoft Visual Studio. Using Visual Studio we can develop our own custom controls for Office tools like Excel, Word and and so on.
In
our demo program We have used Visual Studio 2010 and Office 2007.

Building the Sample

This article explains a few basic things to create our own Custom Add-Ins for Excel and Word as follows.

1. Excel Add-Ins

  • Add text to any Excel selected active Excel cell.
  • Add an image to Excel from our Custom Control.
  • Load data from a database and display the search result data in Excel.

2. Word Add-Ins

  • Export Word to PDF.
  • Add Image to Word Document.
  • Add Table to Word document.

Description

Creating Excel Add-Ins

To create our own Custom Control Add-Ins for Excel.

Step 1

Create a new project and select Office 2007 Excel Add-In as in the following Image. Select your Project Folder and enter your Project Name.

Step 2

Now we can see that the Excel ThisAddIn.Cs file has been created in our project folder and we can find two default methods in this class as in the following image. “ThisAddIn_Startup
In this event we can display our own custom Control Add-Ins to Excel. We can see the details in the code part.

Step 3

Add a new UserControl to your project to create your own Custom Excel Control Add-In.

Right-click your project->Click Add New Item->Add User Control and Name the control as you wish. Add all your Controls and design your user control depending on your requirement.

In our example,We are performing 3 types of actions in User Controls.

  1. Add Text: In this button click event I will insert the text from the Text box to the Active Selected Excel Cell. Using “Globals.ThisAddIn.Application.ActiveCell
    we can get the current active Excel cell. We store the result in an Excel range and now using the range, value and color we can set our own text and colors to the active Excel Cell.

private void btnAddText_Click(object sender, EventArgs e)  

{  

    Excel.Range objRange = Globals.ThisAddIn.Application.ActiveCell;  

    objRange.Interior.Color = Color.Pink; //Active Cell back Color  

    objRange.Borders.Color = Color.Red;// Active Cell border Color  

    objRange.Borders.LineStyle = Excel.XlLineStyle.xlContinuous;  

    objRange.Value = txtActiveCellText.Text; //Active Cell Text Add  

    objRange.Columns.AutoFit();   

}

2.  Add Image: using
the Open File Dialog we can select our own image that needs to be added to the Excel file. Using the Excel.Shape we can add our selected image to the Excel file.

private void btnAddImage_Click(object sender, EventArgs e)  

        {  

            OpenFileDialog dlg = new OpenFileDialog();  

            dlg.FileName = "*";  

            dlg.DefaultExt = "bmp";  

            dlg.ValidateNames = true;  

            dlg.Filter = "Bitmap Image (.bmp)|*.bmp|Gif Image (.gif)|*.gif|JPEG Image (.jpeg)|*.jpeg|Png Image (.png)|*.png";  

            if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)  

            {  

                Bitmap dImg = new Bitmap(dlg.FileName);  

                  Excel.Shape IamgeAdd = Globals.ThisAddIn.Application.ActiveSheet.Shapes.AddPicture(dlg.FileName,  

      Microsoft.Office.Core.MsoTriState.msoFalse,            Microsoft.Office.Core.MsoTriState.msoCTrue,  

          20, 30, dImg.Width, dImg.Height);  

            }  

            System.Windows.Forms.Clipboard.Clear();  

        }

Search and bind Db Data to Excel: Now
we can create our own Custom Search control to be used in Excel to search our data from the database and bind the result to the Excel file.

Creating the table

-- Create Table ItemMaster in your SQL Server - This table will be used for search and bind result to excel.  

CREATE
TABLE
[dbo].[ItemMasters](  

[Item_Code] [varchar](20)
NOT NULL,  

[Item_Name] [varchar](100)
NOT NULL)  

-- insert sample data to Item Master table  

INSERT
INTO
[ItemMasters] ([Item_Code],[Item_Name])  

VALUES
('Item001','Coke')  

INSERT
INTO
[ItemMasters] ([Item_Code],[Item_Name])  

VALUES
('Item002','Coffee')  

INSERT
INTO
[ItemMasters] ([Item_Code],[Item_Name])  

VALUES
('Item003','Chiken Burger')  

INSERT
INTO
[ItemMasters] ([Item_Code],[Item_Name])  

VALUES
('Item004','Potato Fry')

In the button search click event we search for the data from the database and bind the result to an Excel cell using “Globals.ThisAddIn.Application.ActiveSheet.Cells”.
This will add the result to the active Excel sheet.

private
void
btnSearch_Click(
object
sender, EventArgs e)  

{  

    try  

    {  

        System.Data.DataTable dt =
new
System.Data.DataTable();  

        String ConnectionString =
"Data Source=YOURDATASOURCE;Initial Catalog=YOURDATABASENAME;User id = UID;password=password";  

        SqlConnection con =
new
SqlConnection(ConnectionString);  

        String Query =
" Select Item_Code,Item_Name FROM ItemMasters Where Item_Name LIKE '"
+ txtItemName.Text.Trim() + "%'";  

        SqlCommand cmd =
new
SqlCommand(Query, con);  

        cmd.CommandType = System.Data.CommandType.Text;  

        System.Data.SqlClient.SqlDataAdapter sda =
new
System.Data.SqlClient.SqlDataAdapter(cmd);  

        sda.Fill(dt);  

        if
(dt.Rows.Count <= 0)  

        {  

            return;  

        }  

        Globals.ThisAddIn.Application.ActiveSheet.Cells.ClearContents();    

        Globals.ThisAddIn.Application.ActiveSheet.Cells[1, 1].Value2 =
"Item Code";     

        Globals.ThisAddIn.Application.ActiveSheet.Cells[1, 2].Value2 =
"Item Name";     

        for
(int
i = 0; i <= dt.Rows.Count - 1; i++)  

        {     

            Globals.ThisAddIn.Application.ActiveSheet.Cells[i + 2, 1].Value2 = dt.Rows[i][0].ToString();        

            Globals.ThisAddIn.Application.ActiveSheet.Cells[i + 2, 2].Value2 = dt.Rows[i][1].ToString();  

        }  

    }  

    catch
(Exception ex)  

    {  

    }  

}

Step 4

Now we have created our own User Control to be added to our Excel Add-Ins. To add this user control to our Excel Add-In as we have already seen that the Excel Addin class “ThisAddIn.Cs” has start and stop events. Using
the Office “CustomTaskpane” we can add our user control to Excel as an Add-In as in the following.

private
Microsoft.Office.Tools.CustomTaskPane customPane;  

private
void
ThisAddIn_Startup(
object
sender, System.EventArgs e)  

{  

    ShowShanuControl();  

}  

public
void
ShowShanuControl()  

{  

    var txtObject =
new
ShanuExcelADDIn();  

    customPane =
this.CustomTaskPanes.Add(txtObject,
"Enter Text");  

    customPane.Width = txtObject.Width;  

    customPane.Visible =
true;  

}

Step 5

Run your program and now we can see our user control has been added in the Excel File as an Add-In.
Next we will see how to create Add-Ins for Word Documents using a Ribbon Control.

Creating Word Add-Ins: 
In my example I have used Visual Studio 2010 and Office 2007.
The following describes how to create our own Custom Control Add-Ins for Word.

Step 1

Create a new project and select Office 2007 Word AddIn as in the following Image. Select your Project Folder and enter your Project Name.

Step 2

Add a new Ribbon Control to your project to create your own Word Control Add-In.

Right-click your project then click Add New Item -> Add Ribbon Control and name the control as you wish. 

Add all your controls and design your user control depending on your requirements. By default in our Ribbon Control we can see a “RibbonGroup”. We can add all our controls to the Ribbon Group. Here
in my example I have changed the Group Label Text to “SHANU Add-In”. I have added three Ribbon Button Controls to the group. We can add an image to the Ribbon Button Controls and set the properties of the Button Control Size as “
RibbobControlSizeLarge”. 

Here I have added three Button Controls for export the Word as a PDF, add an image to Word and add a table to the Word file.

Step 3

Export to PDF File Button Click.

Using the “Globals.ThisAddIn.Application.ActiveDocument.ExportAsFixedFormat” we can save the Word document to the PDF file. I have used the Save file dialog to save the PDF file into our selected path.

private
void
btnPDF_Click(
object
sender, RibbonControlEventArgs e)  

{  

    SaveFileDialog dlg =
new
SaveFileDialog();  

    dlg.FileName =
"*";  

    dlg.DefaultExt =
"pdf";  

    dlg.ValidateNames =
true;  

    if
(dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)  

    {  

        Globals.ThisAddIn.Application.ActiveDocument.ExportAsFixedFormat(dlg.FileName, word.WdExportFormat.wdExportFormatPDF, OpenAfterExport:
true);  

    }              

}

Step 4

Here we will add an image to Word. Using the Open File Dialog we can select our own image to be added to the Word file. Using the “Globals.ThisAddIn.Application.ActiveDocument.Shapes.AddPicture” method we can add our
selected image to the Word file.

private
void
btnImage_Click(
object
sender, RibbonControlEventArgs e)  

{  

    OpenFileDialog dlg =
new
OpenFileDialog();  

    dlg.FileName =
"*";  

    dlg.DefaultExt =
"bmp";  

    dlg.ValidateNames =
true;  

    dlg.Filter =
"Bitmap Image (.bmp)|*.bmp|Gif Image (.gif)|*.gif|JPEG Image (.jpeg)|*.jpeg|Png Image (.png)|*.png";  

    if
(dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)  

    {  

        Globals.ThisAddIn.Application.ActiveDocument.Shapes.AddPicture(dlg.FileName);  

    }  

}

Step 5

Here we will add a table to Word. Using the “Globals.ThisAddIn.Application.ActiveDocument.Tables” method we can add a table to the Word file. In my example I have created a table with 4 columns and 3 rows.

private
void
button1_Click(
object
sender, RibbonControlEventArgs e)  

{  

    Globals.ThisAddIn.Application.ActiveDocument.Tables.Add(Globals.ThisAddIn.Application.ActiveDocument.Range(0, 0), 3, 4);  

.ThisAddIn.Application.ActiveDocument.Tables[1].Range.Shading.BackgroundPatternColor = Microsoft.Office.Interop.Word.WdColor.wdColorSeaGreen;  

    Globals.ThisAddIn.Application.ActiveDocument.Tables[1].Range.Font.Size = 12;  

    Globals.ThisAddIn.Application.ActiveDocument.Tables[1].Rows.Borders.Enable = 1;  

}

Step 6

Run your program and now you will see your own Ribbon Control has been added to the Word file as an Add-In.

  

You can download the source code from this link Source
Code Link

I’m currently using Visual Studio 2010 Professional, and noticed the ability to create Word 2007 and Word 2010 documents as add-ins with C#.

What I’m looking to do is fill in a report-type document with information in my C# application, and then output the final .docx. Is this possible using this feature, and how do I go about doing it?

Todd Main's user avatar

Todd Main

28.9k11 gold badges82 silver badges146 bronze badges

asked May 27, 2010 at 19:49

Will Eddins's user avatar

What you’re seeing is called VSTO (Visual Studio Tools for Office). It’s a way to create and manage client-instantied add-ins, templates and documents (or, as some do, just control the client for particular operations). It comes with a lot of overhead.

It sounds like what you want instead is the Open XML SDK 2.0. This will give full access to creating Word (and other Office) documents without any need for the Word client or the VSTO requirements (VSTO runtime, Primary Interops, etc.) for the program or on the OS that is creating them. There is a great deal of information out there on the OpenXML SDK — a good starting point is http://www.openxmldeveloper.org. Another, is How-To videos.

answered May 28, 2010 at 17:10

Todd Main's user avatar

Todd MainTodd Main

28.9k11 gold badges82 silver badges146 bronze badges

0

Will,

I have used MS Word’s Content Controls for this purpose. Works better than BookMarks (multiple controls with same name can be populated, unlike bookmarks where repeating data has to have unique bookmark names).

Here is a nice walk-through / tutorial on how to do this step by step using Word 200, C#, ASP.Net (sample code also in there)

Glorfindel's user avatar

Glorfindel

21.7k13 gold badges80 silver badges105 bronze badges

answered Jun 3, 2010 at 19:46

Shiva's user avatar

ShivaShiva

20.3k14 gold badges81 silver badges112 bronze badges

The common way to develop new functionality or custom functionality to outlook, word, excel is to develop COM addins. There are many different different technologies for making these types of addins such as Visual Basic 6.0, Delphi, C++ and .net etc.

If we talk about .NET Then there are two main ways for develop addin:

(a) With thew help of IDTExtensibility interface and other
(b) With the help VSTO(Visual studio tools for office) technology.

VSTO supports both languages VB.net and C# and office 2003 and later version.

this article demonstrate that how to make wordaddin for word 2010 by using vsto 2010.

Objective:

Showing Welcome message on word application start up

Start project:

Start vsto project File — > New project — > installed Template — >  Visual C# — >  office — > 2010

Select Word 2010 add-in

Start the Word Add In

Visual studio automatically generate thisAddin.vb class( thisaddin.vb in vb.net and thisaddin.cs in C#.). we can see this class in our project. We can use this class to perform various task such as customizing the user interface of the word application , accessing object model of office host application(ih this project microsoft is the host application) etc. this type of addin is also called by ‘application label addin’.

There are two default event handlers in this class one is ThisAddin_Startup and other is ThisAddin_ShutDown.

Vsto addin use object model of host application, means if we are working for outlook addin in vsto then addin will use outlook object model or if we are working in word addin project then addin application will use word object model so our addin application will use Word Object Model.

So right now  I am telling about some important  things about word object model

Word object model consists of classes and interfaces that are provided in the primary interop assembly for Word, and are defined in the Microsoft,office,Interop.Word namespace.

The following sections briefly describe the top-level objects of word object model and how they interact with each other. These objects include the following five:

  • Application object
  • Document object
  • Selection object
  • Range object
  • Bookmark object

Application Object

The Application object represents the Word application, and it is root object of other objects. We can use its properties and methods to control the Word application.

Document Object

Document object represents a document and all of its contents. When you open a document or create a new document, you create a new Microsoft,office,Interop.Word.document object, which is added to the Documents collection of the Application object. The document that has the focus is called the active document. It is represented by the ActiveDocument property of the Application object.

Selection Object

The Selection object represents the current selected area. When you perform an operation in the Word user interface, such as bolding text, you select, or highlight the text and then apply the formatting

Range Object

The Range object represents a contiguous area in a document, and is defined by a starting character position and an ending character position.

Content Control Objects

A Microsoft,office,Interop.Word.ContentControl provides a way for you to control the input and presentation of text and other types of content in Word documents. Such as richtext contentcontrol,plaintext content control…

And Now edit the ThisAddIn class for showing welcome message on the add in start up routine.
Code:

public partial class ThisAddIn
{
Private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
MessageBox.Show("Welcome to My Word Add-in");
}
private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
{
}
}

Run Addin:

Download attached project and build project

Download Source code

Like this post? Please share to your friends:
  • Visual studio 2008 excel
  • Visual representation of a word
  • Visual basic через excel
  • Visual basic функции примеры excel
  • Visual basic макрос для word