Creating an Instance of an Automation Server






Creating an Instance of an Automation Server

Referencing a type library allows Visual C# to integrate the available objects of the type library with its own internal objects. After this is done, you can create object variables based on object types found in the type library. Excel has an object called Application, which acts as the primary object in the Excel object model. In fact, most Office programs have an Application object. How do you know what objects an automation server supports? The only sure way is to consult the documentation of the program in question or use the Object Browser discussed in Hour 3, "Understanding Objects and Collections."

By the Way

In this example, you'll be using about a half-dozen members of an Excel object. This doesn't even begin to scratch the surface of Excel's object model, nor is it intended to. What you should learn from this example is the mechanics of working with an automation server. If you choose to automate a program in your own projects, consult the program's developer documentation to learn as much about its object model as you canyou're sure to be surprised at the functionality available to you.


In order to use the COM reference you created, you need to add a using statement to your class. Begin by double-clicking the button to access its Click event, and then scroll up to the top of the class and add this using statement, right below the existing using statements:

using Excel;

Next, enter the following code, which creates a new Excel Application object into the btnAutomaticeExcel_Click event:

Excel.Application objExcel = new Excel.Application();

Notice that Visual C# included Excel in its IntelliSense drop-down list of available objects. It could do this because you referenced Excel's type library and created the using statement. If you neglected to do either of these two things, Excel would not show up and the code would not work. Excel is the reference to the server, and Application is an object supported by the server. This statement creates a new Application object based on the Excel object model.



 Python   SQL   Java   php   Perl 
 game development   web development   internet   *nix   graphics   hardware 
 telecommunications   C++ 
 Flash   Active Directory   Windows