excel|visual|word| programming
Example 3: Open an existing Word document
With Documents.saveasMethod, Documents.OpenThe method signature is also different between Office 2000 and OfficeXP, so the new name is wrapped in the #ifDeclaration. OpenMethods and SaveAsMethod is as simple as the following:
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,#endif ref optional, ref optional, ref optional, ref optional, ref optional, ref optional, ref optional, ref optional, ref optional, ref optional, ref optional);
Word 2002 in Help for Visual Basic Reference and MSDN (English)
Documents.OpenThe instructions for the method record these optional parameters.
The more interesting code in this example is that the text in the open document is highlighted first and then cut:
Object first=0; Object Last=doc. Characters.count; Range r = Doc. Range (ref, ref, last); R.select (); Thread.Sleep (2000); R.cut ();
The integer value of the first and last character positions is encapsulated into the first and last object, and then passed to the Document.range () function, which returns the function call of the RangeObject. This type of explicit encapsulation is required because RangeObjects are expected to reference their arguments, and any implicit or explicit conversion changes the argument to a right value and the right value cannot be passed by reference. This example causes the text to be highlighted for two seconds, and then the text is clipped. The cut operation can also be implemented through the following code:
Object first=0; Object units = Wdunits.wdcharacter; Object Last=doc. Characters.count; Doc. Range (ref, ref, last). Delete (ref units, ref last);
How to build and run Example3.cs
To generate a example3.cs, you can
Visual Studio. NET Command PromptIn the Visual Studio. NET Command Prompt window, do the following:
- Open the directory where you saved the Example3.cs source file (for example, C:\CSOfficeSamples) and type csc/r after the command prompt : "C:\Office XP pias\ Microsoft.Office.Interop.Word.dll "/d:officexp Example3.cs.
(If the Office XP PIA is saved in a different location, you will need to replace the following drive and installation paths with the corresponding values:csc/r: Drive:\< installation path >\microsoft.office.interop.word.dll/ D:officexp Example3.cs. )
- To run Example3.exe (located in the same folder as the Example3.cs source file), double-click the program.
Example 4: Events that are exposed using Word
This example involves more than a few other things, but it's not really complicated. The main reason for looking complex is that the name of an event and its handler type is longer. Take a look at the Office XP version of DocumentOpenAnd DocumentChangeSetting code for the event handler:
... #if officexp applicationevents3_documentopeneventhandler myopendoc = new Applicationevents3_documentopenevent Handler (Myopeneventhandler); ApplicationEvents3_DocumentChangeEventHandler myChangeDoc = new ApplicationEvents3_DocumentChangeEventHandler (DocC hange); #else.
These two statements are just the event handlers that declare the event. In the next few lines of code, these handlers are assigned to the ApplicationEvents in the Object app:
App. DocumentOpen + = Myopendoc; App. DocumentChange + = myChangeDoc;
You can use these two events now. Call
Openmethod, both events are raised at the same time. Open the hyperlink in turn read the documentation for the DocumentOpen (English) and DocumentChange (English) methods.
So, how do you know which events are available and how they are invoked by handlers? If you use ILDASM to check Word 2002 PIA (Microsoft.Office.Interop.Word.dll), you will find that you have a green inverted triangle marked in front of some types. The flag indicates that the member is an event. Figure 4 shows the help for the ILDASM tree view icon.
Figure 4:ildasm tree view icon Help
Figure 5: Using ILDASM to view the events of the Application object (click picture to view large image)
Figure 5 shows a partial screenshot of the event for the Application object. The leftmost identifier for each row is the event name. To the right of the colon is the fully qualified type name of the event handler. For example, the DocumentBeforeSave event requires the following types of handlers:
Microsoft.Office.Interop.Word. Applicationevents3_documentbeforesaveeventhandler
Please note that the event does not tell us any information about the signature of the event handler. Therefore, you need to look at the event handler declaration. In ILDASM, if you double-click
Applicationevents3_documentbeforesaveeventhandlerType, you will see a similar
Figure 6The content that is displayed.
Figure 6: Viewing an event handler declaration in ILDASM
What's interesting to us is that InvokeMethod. 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 Word 2002 Visual Basic documents. For DocumentBeforeSaveEvents, documents (in English) are described as follows:
Private Sub Object_documentbeforesave (ByVal Doc as Document, SaveAsUi as Boolean, Cancel as Boolean)
The document then describes the meaning of each parameter. Keep in mind that C # passes parameters by value by default, and Visual Basic passes parameters by reference by default. That's why two BooleanThe parameters are followed by the & symbol when they are displayed in ILDASM, but are used in C # with the keyword refThe reason for the tag. Similarly, in Visual Basic, the Subsis considered as a method of returning void in C #. So DocumentsaveThe handler for the event should resemble the following:
public static void Savehandler (document DOC, ref bool B1, ref bool B2) {MessageBox.Show ("Saving document", "document Save event ", MessageBoxButtons.OK, MessageBoxIcon.Information);}
When by calling
SaveAsmethod when you save a document
DocumentBeforeSaveEvent is raised before the document is saved.
In SaveAsYou will see the following code fragment in the next few lines of code for the method call:
App. DocumentChange-= myChangeDoc;
This line of code is decoupled from the
DocumentChangeevent, so that the event will not be called in the
QuitPeriod was raised.
How to build and run Example4.cs
To generate a example4.cs, you can
Visual Studio. NET Command PromptIn the Visual Studio. NET Command Prompt window, do the following:
- Open the directory where you saved the Example4.cs source file (for example, C:\CSOfficeSamples) and type csc/r after the command prompt : "C:\Office XP pias\ Microsoft.Office.Interop.Word.dll "/d:officexp Example4.cs.
(If the Office XP PIA is saved in a different location, you will need to replace the following drive and installation paths with the corresponding values:csc/r: Drive:\< installation path >\microsoft.office.interop.word.dll/ D:officexp Example4.cs. )
- To run Example4.exe (located in the same folder as the Example4.cs source file), double-click the program.
Example 5: Animate the Office Assistant
Some people like Office assistants, and some hate them. In any case, Example5.cs here is just to add a little fun. This sample program also uses the assistant type information that is located in Mso.dll. The program uses two PIAs:
- Microsoft.Office.Interop.Word.dll
- Office.dll
Each important step in the Example5.cs source file is commented on in detail. This code is not intended to be introduced here because it is easy to understand.
How to build and run Example5.cs
To generate a example5.cs, you can
Visual Studio. NET Command PromptIn the Visual Studio. NET Command Prompt window, do the following:
- Open the directory where you saved the Example5.cs source file (for example, the C:\CSOfficeSamples directory) and type csc/r after the command prompt : "C:\Office XP pias\ Microsoft.Office.Interop.Word.dll "/r: C:\Office XP pias\office.dll" Example5.cs.
(If the Office XP PIA is saved in a different location, you will need to replace the following drive and installation paths with the corresponding values:csc/r: Drive:\< installation path >\microsoft.office.interop.word.dll/ r:drive:\< installation path >\office.dll Example5.cs. )
- To run Example5.exe (located in the same folder as the Example5.cs source file), double-click the program.
Example 6: Default Properties and Indexed properties
This example (Excel1.cs) takes advantage of the fact that Word 2002 rarely uses default properties and indexed properties, and Excel 2002 often uses them.
Like all Office XP interop codes, the example program starts with instantiating the Application object. After you create a workbook and worksheet, you create an array of strings to hold the column headers. After you create the array, you will see the following code fragment:
Wksrange = Wks.get_range ("A2", "D2");
This code gets the Range object for cell A2 to D2. But since the worksheet has a Range property, why do I need to call the Access function directly? And why doesn't it make grammatical mistakes as usual?
Unlike visual Basic and Visual C + +, C # does not have a syntax structure that applies to indexed properties. To use indexed properties in C #, you must call the Access function directly.
_worksheet.rangeThe attribute is a good example. To obtain in Visual C + +
Rangeproperty, the code should look like the following:
MyRange = myworksheet->range["A2", "D2"];
To perform the same action in C #, the code should look like this:
MyRange = Myworksheet.get_range ("A2", "D2");
Set up
Rangeproperty, rather than assigning it to it, is a call to the set access function:
Myworksheet.set_range ("A2", "D2", MyRange);
In Microsoft Excel 2000,
Range.valueproperty is a general property, but in Excel 2002, it becomes an indexed property. This is why you should enclose this property in #if officexp statement in this sample program.
_workbook.worksheetsHas the so-called default properties. Default properties are considered to be properties in an interop assembly that are named Item. You usually have to specify an Item member to use the default property from C #, but in an Excel library, TLBIMP can create a small amount of code that is called
Get__defaultOr
Set__default's Access function. If these two access functions exist, C # can use the Index builder syntax instead of calling the access function directly. 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 build and run Excel1.cs
To generate a excel1.cs, you can
Visual Studio. NET Command PromptIn the Visual Studio. NET Command Prompt window, do the following:
- Open the directory where you saved the Excel1.cs source file (for example, the C:\CSOfficeSamples directory) and type csc/r after the command prompt : C:\Office XP pias\ Microsoft.Office.Interop.Excel.dll "/d:officexp Excel1.cs.
(If the Office XP PIA is saved in a different location, you will need to replace the following drive and installation paths with the corresponding values:csc/r: Drive:\< Installation path >\microsoft.office.interop.excel.dll /d:officexp Excel1.cs. )
- To run Excel1.exe (located in the same folder as the Excel1.cs source file), double-click the program.
Summary
C # COM Interop is a useful tool because it allows you to use existing objects directly without rewriting the code for those objects. This article can help you take advantage of existing COM object code.
Here are links to articles about PIA,. NET security,. NET, and COM interop, where you can get more detailed information.
- Introduction to COM Interop (English)
- Primary Interop Assemblies (PIAs) (English)
- Microsoft. NET Framework FAQ (English)
- Microsoft. Net/com Migration and Interoperability (English)
- . NET Interop:get Ready for Microsoft. NET by Using Wrappers to interact with com-based applications (English)
- Exposing. NET Framework components to COM (English)
- Calling A. NET Component from a COM Component (English)
- Calling COM components from. NET Clients (English)