Summary: Learn about COM interoperability between Microsoft C # and large complex COM servers. This article describes how to prepare the Office XP COM object and how to use these objects in the C # program, and provide some prompts to help you understand why some operations must be implemented through a specific approach.
Introduction
One of the most powerful features of Microsoft® Office XP is its components (such as Microsoft Excel 2002 and Microsoft Word 2002) to disclose its function as a component object model (COM) interface. Accessing these COM interfaces via Microsoft Visual Basic® 6.0 is relatively easy, but it is more difficult to use these interfaces and public classes through C or C . However, Microsoft C or Microsoft Visual C ® with hosted extensions can easily use Office XP public COM objects like Visual Basic 6.0.
This article assumes that you want Office XP programming. Although this document provides the hyperlink of the MSDN® document, you should have a content introduced herein, you should be familiar with or can access the Office XP programming document.
This document describes the interfaces and public categories provided by Office XP and their usage. The documentation is expressed in the form of Visual Basic programming languages, so you need to convert in your mind and event signature. This article describes how this conversion is prepared for the Office XP COM object, and how to use these COM objects in the C # program. Finally, this article also provides some tips to help you understand why some operations must be implemented through a specific approach. With this information, you should be able to take advantage of other COM servers using C #.
System Requirements
To run an example, you need to install the following software on your computer:
Microsoft Windows® XP or Microsoft Windows 2000 and related Service Pack (SP) Microsoft Office XP and associated SP Microsoft .NET Framework (English) and associated SP Microsoft Office XP Primary Interop Assemblies (PIA) (English) Microsoft Visual Studio® .NET
Some quick entry knowledge of .NET
.NET technology introduces the concept of an assembly and uses it as a basic executable unit. The assembly can be an executable file (.exe) or a dynamic link library (.dll) and can contain multiple files. The assembly contains all information about the code, types, and resources required to run the program.
To use Office XP disclosed COM objects, you need to use the primary interoperable assembly (PIA) so that the C # compiler can find the interfaces and public classes disclosed in Office XP.
This article will not be described in detail on interoperability assembly or PIA.
Understand that the disclosed type information is usually given some inspiration. Microsoft Visual Studio® .NET provides a tool called ILDASM to list type information encapsulated in the assembly. Figure 1 is a partial screen pick-up of ILDASM display Word 2002 primary operational assembly information.
Note: To open the ILDASM tool, click Start, point to "Programs", point to "Microsoft Visual Studio .Net", point to Visual Studio .Net Tools and click
Visual Studio .NET Command Prompt (Visual Studio .NET Command Tips). in
Visual Studio .NET Command Prompt (Visual Studio .NET Command prompt) window, type
ILDASM. The ILDASM window is then opened. To see a specific interoperability assembly or PIA type information,
File (File) menu, click
Open. Browse to the location of the interoperable assembly or PIA, select the interoperable assembly or PIA you want to view and click
Open.
Figure 1: Use the ILDASM tool to view the type information of the interoperable assembly
As shown in Figure 1, the assembly is located in Microsoft.Office.Interop.Word.dll, while the interfaces and public classes are encapsulated in the Microsoft.Office.Interop.Word namespace. Application public category has been expanded, which can be seen, it extends (according to C and C # terms, derived) Application, and implements ApplicationEvents2_event interface in Word. All of this will be discussed in detail in this article.
Use Office XP Main Interoperable Settings
Before running the examples included in this article, Microsoft Office XP Primary Interop Assemblies (PIAs) should be installed on your computer. After installing the PIA, it must be placed in the compiler and the completed programs can be accessed. For more information, see the readme file and ".NET Framework Developer's Guide" included in the Office XP PIA download document (to read it, click "Start", point to "Programs", then point to Microsoft .NET Framework SDK and single "Assembly Location" in Documentation [Document]).
For the purpose of the presentation, the Office XP PIA is decompressed to the following folders: C: / Office XP PIAS /. Then install it to the global assembly cache (GAC) and register.
This compiler can be called by typing the executable file name (csc.exe) of the command line to the C # compiler. After installing and registering the PIA, you can use the / R option, which is referenced on the CSC command line just like reference to any additional assemblies. If the location of the PIA cannot be accessed, the program will fail at runtime and generate a system.io.filenotFoundException or System.TypeInitializationException type exception, which assembly cannot be loaded.
Next, in the section "How to Compile and Run Example1.cs", you will show you how to generate C # programs and reference PIAs using the command line.
The examples included in this article use three Office XP PIA:
Microsoft.Office.Interop.Word.dll Office.dll Microsoft.Office.Interop.Excel.dll code drill
Before presentation code example, you should first download the ODC_OFFCS.EXE file and extract the sample program to C: / csofficesamples or you select. In order to facilitate reference, in all examples below, it is assumed that the sample program is located in the C: / CSOFFICSAMPLES directory.
Download documents contain five Word 2002 sample programs (Example1.cs, Example2.cs, Example3.cs, Example4.cs, and Example5.cs) and an Excel 2002 sample program (Excel1.cs). The corresponding example generated file of the exemplary source file is also included in it for readers.
All code examples have made detailed comments.
Example 1: Start the Word Application object
The first example is very simple, only how to start Word 2002 and keep it open in a few seconds, and then turn it off. First take a look at the main code line in the Example1.cs source file. The following code snippet assigns Application objects and its base class object, but in actually CoCreateInstance calls.
Application App = New Application (); the Quit method for the Application class accepts three parameters: SaveChanges, OriginalFormat, and ROUTEDocument. These optional parameters can be omitted in the Visual Basic code, and there is no optional parameters in C #; all three parameters must be passed to Quit during call. The same effect can be obtained by assigning Value missing.Value to each optional variable (for notifying the quit method using the default behavior). In this example, ie, "does not save the document, the initial format of the document, and does not perform routing".
Object savechanges = missing.value; object originalformat = missing.value; object routedocument = missing.value; app.quit (ref savechanges, ref originalformat, ref routedocument);
Note that all three parameters are labeled REF keywords. Since these methods were initially written in Visual Basic, the Visual Basic was transferred by default to pass the parameters. Therefore, the parameters must also be transmitted according to the reference.
How to generate and run example1.cs
To run this example, first generate an example of an examle1.cs. To generate this example in Visual Studio .NET Command Prompt window:
Go to the C: / CSOFFICSAMPLES directory or save any directory of the example. As shown in Figure 2, type CD C: / CSOFFICSAMPLES after the command prompt. Then, in the command prompt shown in FIG. 2, type CSC / R: "C: / Office XP PIAS / Microsoft.Office.Interop.word.dll" Example1.cs Generates Example1.cs. (If Office XP PIA is saved in other locations, you need to replace the following "Drives" and "Installation Path": CSC / R: Drive: / Microsoft.Office.Interop.Word.dll Example1. CS.) Note: The command line CSC compiles the Example1.cs source file to generate the example1.exe executable. In this example, the created executable will automatically save in the same folder in Example1.cs. Command line options / r will reference Microsoft.Office.Interop.Word.dll. If the path of Microsoft.Office.Interop.Word.dll PIA appears error, the program will fail at runtime, and generate a system.io.filenotFoundException or System.TypeinitializationException type exception, which Components cannot be loaded.
Figure 2: Bringing the program in the same folder using the command line to generate the source file.
This example is a very simple program that does not have any functions that make people interested, let us take a look at Example 2.
Example 2: Creating a new Word document
Example2.cs is the same as example 1, but also to start Word 2002 using the Application object, then add a new document in the open document (the collection package in the Application.Documents property). The first meaningful code snippet appears when creating a new document:
object template = Missing.Value; object newTemplate = Missing.Value; object documentType = Missing.Value; object visible = true; _Document doc = app.Documents.Add (ref template, ref newTemplate, ref documentType, Ref visible); font>
All parameters of the Add method are optional, so you must specify a meaningful value or specify Missing.Value. In this example, since we don't need to use or create a template, it is just a plain text document, set the top three parameters (Template, NewTemplate, and DocumentType) to missing.value. Since this document is desired to be visible in this example, the parameter Visible is set to "True".
You may make up how you determine if you should assure the Boolean value to the Visible object. That's why I have access to the Word 2002 programming document is very important. If you look at the description of the Documents.Add method in the Word 2002 Object Model Document, you will see the following: Visible optional Variant. Set to True will open the document in a visible window. If the value is false, Microsoft Word will open the document, but set the Visible property of the document window to false. The default is TRUE.
Note: To view the Word 2002 Visual Basic documentation
Documents.add method, you can select "Macro" in the Tools menu of Word 2002, then click Visual Basic Editor. When you are in the keyboard status of the Visual Basic Editor, press
F2 key activates "object browser" or press
The F1 key is "Help". Then search "Documents" or "Documents.Add". Similar documents can also be found on the MSDN.
This avoids a problem: Why is the PIA expects the parameter type of the add method to object, and the document is displayed by the Documents.Add method document. This is because the variant type is automatically encapsulated as the .NET Object object type, the latter maps to the Object type of C #. In this example, parameter Visible encapsulates the Boolean value true to Object and passes it to the documents.add () function.
The next important code is:
Doc.Words.First.Insertbefore
Use the document interface returned from the app.Documents.add () function to the documentation, add some text at the beginning of the document. There is no special place here.
Let's take a look at the code snippet, which is more interested, and its role is to save the document:
object fileName = Environment.CurrentDirectory "// example2_new"; # if OFFICEXPdoc.SaveAs2000 (ref fileName, # elsedoc.SaveAs (ref fileName, # endifref optional, ref optional, ref optional, ref optional, ref optional , Ref Optional, Ref Optional, Ref Optional, Ref Optional, Ref Optional; font>
One thing you want to pay attention to is that the string of saving file names is encapsulated into the FileName object. Second, this code will call the SaveAs2000 method in the case where Officexp is defined, and the SaveAs method is called without defining OFFICEXP. Perhaps you have already guessed that there is a difference between the SaveAs method signing between Office 2000 and Office XP.
How to generate and run example2.cs
To generate xample2.cs, you can do the following in the Visual Studio .NET Command PROMPT window:
In the directory of the C: / CSOFFicesamples Directory, or any saved example2.cs, type CSC / R: "C: / Office XP Pias / Microsoft.Office.Interop.Word.dll" / D: OFFICEXP EXAMPLE2.CS. (If Office XP PIA is saved in other locations, you need to replace the following "drive" and "Installation Path": CSC / R: Drive: / Microsoft.Office.Interop.Word.dll / D : OFFICEXP EXAMPLE2.CS.) Figure 3: Using the command line to compile EXAMPLE2.CS To run Example2.exe (in the same folder with the eXample2.cs source file), double-click the program. Example 3: Open an existing Word document
Like the documents.saveas method, there is also a difference between the Documents.open method sign between Office 2000 and OfficeXP, so the new name package is in the #IF declaration. The OPEN method is as simple as the SaveAs method, as shown below:
object fileName = Environment.CurrentDirectory "// example3"; object optional = Missing.Value; #if OFFICEXP_Document doc = app.Documents.Open2000 (ref fileName, # else_Document doc = app.Documents.Open (ref Filename, # endifref Optional, Ref Optional, Ref Optional, Ref Optional, Ref Optional, Ref Optional, Ref Optional, Ref Optional, Ref Optional, Ref Optional, Ref Optional; font>
These optional parameters are recorded in the Word 2002 Visual Basic reference and MSDN (English) for the MSDN (English). These optional parameters are recorded.
The code that is more interest in this example is that the text in the open document is first highlighted and then cut:
Object first = 0; object last = doc.characters.count; Range r = doc.range (ref first, ref at); r.select (); thread.sleep (2000); r.cut (); Font>
The integer value of the first character and the last character position is packaged to the first and last object, and then passed to the document.range () function, which returns the range object that the SELECT () function calls. This explicit package is required because the RANGE object is expected to reference its parameters, and any implicit or explicit conversions will be changed to the right value, and the right value cannot be passed according to the reference. This example makes text highlights last for two seconds, and then cuts text. Shearing operation can also be implemented by the following code: Object first = 0; Object units = wdunits.wdcharacter; object last = doc.characters.count; Doc.Range (Ref first, ref Last) .delete (Ref units, ref Last) ;
How to generate and run example3.cs
To generate an example3.cs, you can do the following in the Visual Studio .NET Command Prompt window:
Turn on the directory (for example, c: / csofficesamples) saved in the example3.cs source file, and type CSC / R after command prompt: "c: / office xp pias / microsoft.office.interop.word.dll" / d: Officexp Example3 . (If Office XP PIA is saved in other locations, you need to replace the following "drive" and "Installation Path": CSC / R: Drive: / Microsoft.Office.Interop.Word.dll / D : Officexp Example3.cs.) To run Example3.exe (in the same folder with the eXample3.cs source file), double-click the program.
Example 4: Events using Word
The content involved in this example is more than a few more, but it is actually not complicated. It seems that the complicated main reason is that the name of the identification event and its handler type is longer. Take a look at the setup code for Office XP version of Documentopen and DocumentChange event handler:
... #if OFFICEXP ApplicationEvents3_DocumentOpenEventHandler myOpenDoc = new ApplicationEvents3_DocumentOpenEventHandler (MyOpenEventHandler); ApplicationEvents3_DocumentChangeEventHandler myChangeDoc = new ApplicationEvents3_DocumentChangeEventHandler (DocChange); #else ...
These two statements are merely an event handler that declares events. In the subsequent line of code, these processing programs will be specified to an event in the Application object app: app.documentopen = myopendoc; app.documentchange = mychangedoc;
You can use these two events now. These two events will be triggered when calling the Open method. Open the hyperlink to read the documentation on Documentopen and DocumentChange (English) methods. So, how do you know which events can be available with the calling method of their handroots? If you use ILDASM to check Word 2002 PIA (Microsoft.Office.Interop.Word.dll), it will find that in some types of front labeled green fall triangle signs. This flag indicates that a member is an event. Figure 4 shows the help of the ILDASM tree view icon.
Figure 4: Ildasm tree view icon help
Figure 5: Events using ILDASM to view Application objects
Figure 5 shows a partial screen snapshot of an event of an Application object. The leftmost identifier per line is the event name. The right side of the colon is the full qualified type name of the event handler. For example, the DocumentBeforeSave event requires the following types of handlers:
Microsoft.Office.Interop.Word.ApplicationEvents3_DocumentbeforeesaveEventhandler
Note that the event does not tell us any information about the event handler signature. Therefore, you need to take a look at the event handler declaration. In ILDASM, if you double-click ApplicationEventS3_DocumentBeforeSaveEventHandler type, you will see the content similar to Figure 6 display.
Figure 6: Viewing event handler declarations in ILDASM
Let us interested in the Invoke method. A function written for an event handler must have this signature. But how do you know the meaning of the parameter and the value it uses? This is the importance of the Word 2002 Visual Basic document. For the DocumentBeforeSave event, the document (English) is described below:
Private Sub Object_DocumentBeforeSave (Byval Doc as Document, Saveasui Asboolean, Cancel As Boolean)
This document will then describe the meaning of each parameter. Keep in mind that C # is passed by value by default, and Visual Basic passes the parameters by default. That's why two Boolean parameters are used with & symbols when they are displayed with ILDASM, while using the keyword REF tag when used in C #. Similarly, SUBS in Visual Basic is seen as a method of returning Void in C #. Therefore, the handler of the Documentsave event should be similar to:
Public Static Void SaveHandler (Document Doc, Ref Bool B1, Ref Bool B2) {MessageBox.Show ("Saving Document", "Documentsave Event", MessageBoxButtons.ok, MessageBoxicon.information;
When the document is saved by calling the SaveAs method, the DocumentBeforeSave event will trigger before saving the document.
In the back of the SaveAs method call, you will see the following code snippet:
app.documentchange - = mychangedoc;
This code line releases the hook of the DocumentChange event so that this event will not be triggered during the call. How to generate and run example4.cs
To generate an example4.cs, you can do the following in the Visual Studio .NET Command PROMPT window:
Turn on the directory (for example, c: / csofficesamples) saved in the Example4.cs source file, and type CSC / R after command prompt: "c: / office xp pias / microsoft.office.interop.word.dll" / d: Officexp Example4 . (If Office XP PIA is saved in other locations, you need to replace the following "drive" and "Installation Path": CSC / R: Drive: / Microsoft.Office.Interop.Word.dll / d: / Microsoft.Office.Interop.Word.dll / D : Officexp Example4.cs.) To run Example4.exe (located in the same folder with the eXample4.cs source file), double-click the program.
Example 5: Animation shows Office Assistant
Some users like Office assistants, some people hate them. In any case, Example5.cs are just in order to add a little fun. This sample program also uses assistant type information located in MSO.dll. This program uses two PIAs:
Microsoft.Office.Interop.Word.dll Office.dll
Each important step in the Example5.cs source file has been detailed. This code is not prepared here because it is easy to understand.
How to generate and run example5.cs
To generate example5.cs, you can do the following in the Visual Studio .NET Command PROMPT window:
Turn on the directory where the Example5.cs source file (eg C: / csofficesamples directory) is turned on, and type CSC / R after command prompt: "C: / office XP pias / microsoft.office.interop.word.dll" / r: " C: / office xp pias / office.dll "example5.cs. (If Office XP PIA is saved in other locations, you need to replace the following "Drives" and "Installation Path": CSC / R: Drive: / Microsoft.Office.Interop.Word.dll / R : Drive: /
Example 6: Default Properties and Index Properties
Word 2002 rarely uses default properties and index properties, and Excel 2002 often uses them, so this example (Excel1.cs) uses this fact.
Like all Office XP interoperability, this sample program starts from instantiation Application objects. After creating a workbook and a worksheet, a string array for saving the column header is created. After you create the array, you will see the following code snippet:
WKSRANGE = WKS.GET_RANGE ("A2", "D2"); this code acquires the RANGE object of cell A2 to D2. But since the worksheet has a Range property, why does I need to call access functions directly? And so if you are not like usually a syntax error?
Unlike Visual Basic and Visual C , C # does not apply to the syntax structure for index properties. To use index properties in C #, the access function must be called directly. _Worksheet.Range properties are a good example. To get the value of the Range property in Visual C , the code should look like this:
MyRange = myworksheet-> range ["A2", "D2"];
To perform the same operation in C #, the code should be as follows:
MyRange = myworksheet.get_range ("a2", "d2");
Set the range property instead of assigning it, it is called the SET Access function:
Myworksheet.set_range ("a2", "d2", myrange);
The Range.Value property in Microsoft Excel 2000 is a regular properties, but in Excel 2002, it becomes an index property. This is why it is enclosed in the #if officexp statement when using this property in this sample program.
_Workbook.Worksheets has a so-called default properties. The default attribute is considered to be the attribute name Item in the interoperable program. You usually have to specify the Item member to use the default properties from the C #, but in the Excel library, TLBIMP can create access functions called GET__DEFAULT or SET_DEFAUULT only a small amount of code. If these two access functions exist, C # can use the index generator syntax instead of directly call the access function. The two lines of code in this example are as follows:
_Worksheet WKS2 = (_Worksheet) WKB.Worksheets ["Market Share!"]; (_ Worksheet) WKB.Worksheets ["Market Share!"]). Name = "fred";
How to generate and run Excel1.cs
To generate Excel1.cs, you can do the following in the Visual Studio .NET Command PROMPT window:
Open the directory where the Excel1.cs source file (for example, a C: / csofficesamples directory), type CSC / R after command prompt: "c: / office xp pias / microsoft.office.interop.Excel.dll" / d: Officexp Excel1 . (If Office XP PIA is saved in other locations, you need to replace the following "Drives" and "Installation Path": CSC / R: Drive: / Microsoft.Office.Interop.Excel.dll / d: / Microsoft.Office.Interop.Excel.dll / D : Officexp Excel1.cs.) To run Excel1.exe (in the same folder with the Excel1.cs source file), double-click the program. summary
C # COM interoperability is a very useful tool because it can be rewritten for those objects without using existing objects directly. This article helps you use the existing COM object code.