Tải bản đầy đủ - 0 (trang)
Hour 20. Controlling Other Applications Using Automation

Hour 20. Controlling Other Applications Using Automation

Tải bản đầy đủ - 0trang

Hour20.ControllingOtherApplicationsUsing

Automation

In Hour 17, "Designing Objects Using Classes," you

learned how to use classes to create objects. In that

hour, I mentioned that objects could be exposed to

outside applications—Excel, for example, exposes

most of its functionality as a set of objects. The

process of using objects from another application is

called Automation. The externally accessible objects

of an application compose its object model. Using

Automation to manipulate a program's object model

enables you to reuse components. For instance, you

can use Automation with Excel to perform complex

mathematical functions using the code that's been

writtenandtestedwithinExcel,ratherthanhavingto

writeanddebugthecomplexcodeyourself.

Programs that expose objects are called servers, and the

programs that consume those objects are called clients.

Creatingautomationserversrequiresadvancedskills,including

a very thorough understanding of programming classes.

Creating clients to use objects from other applications, on the

otherhand,isrelativelysimple.Inthishour,you'lllearnhowto

create a client application that uses objects of an external

serverapplication.

Thehighlightsofthishourincludethefollowing:

Creatingareferencetoanautomationlibrary



Creatinganinstanceofanautomationserver

Manipulatingtheobjectsofanautomationserver

To understand Automation, you're going to build a Microsoft

Excelclient—aprogramthatautomatesExcelviaExcel'sobject

model.



This exercise is designed to work with Excel 2000 or

Excel XP. If you don't have Excel installed on your

computer,youwon'tbeabletocompletetheexercise.

Create a new Windows Application named Automate Excel.

Change the name of the default form to fclsMain, set its Text

property to Automate Excel, and then set the entry point in

Main() to reference fclsMain instead of Form1. Next, add a

button to the form by double-clicking the Button item in the

toolboxandsetthebutton'spropertiesasfollows:

Property

Name

Location

Size

Text



Value



btnAutomateExcel

96,128

104,23

AutomateExcel







Top











CreatingaReferencetoanAutomationLibrary

To use the objects of a program that supports

Automation (a server), you have to reference the

program'stypelibrary.Aprogram'stypelibrary(also

called object library) is a file that contains a

descriptionoftheprogram'sobjectmodel.Afteryou've

referenced the type library of an automation server

(alsocalledacomponent),youcanaccesstheobjects

oftheserverasthoughtheywereinternalC#objects.

Tocreateareferencetoatypelibrary,firstdisplaythe

AddReferencedialogboxbychoosingAddReference

from the Project menu (do this now). A number of

types of components support automation. Of course,

.NETisthelatesttechnology,butinthecaseofExcel,

we'reinterestedintheCOMcomponents.COMstands

for Component Object Model, and it's been the

technology for working with objects within windows

formanyyears.Microsoft's.NETplatformisdesigned

toreplaceCOM.Thisisn'tgoingtohappenovernight,

however; literally thousands of objects are built on

COM technology. In fact, all the Microsoft Office

products up to and including Office XP are based on

COM.

ClicktheCOMtabnowtodisplaytheavailableCOMcomponents

(programs that have a type library) on your computer. Scroll



thelistandlocatetheMicrosoftExcelXObjectLibrary(whereX

istheversionofExcelinstalledonyourcomputer).Double-click

theExcelitemtoaddittothelistofselectedcomponentsatthe

bottomoftheAddReferencedialogbox(seeFigure20.1).

Figure20.1.Touseanobjectlibrary,youneedto

referenceitfirst.



If you don't see an entry for Microsoft Excel, you

probablydon'thaveExcelinstalledonyourcomputer;

therefore,thiscodewon'twork.

ClickOKnowtoaddthereferencetoyourproject.C#

doesn'tworkdirectlywithCOMcomponents.Instead,

it interacts through a wrapper, a set of code and

objectsthatworksasanintermediarybetweenC#and



a COM component. Chances are that your machine

doesn't have an existing wrapper for Excel; if this is

the case, C# automatically creates the wrapper and

referencesthecomponent.









Top











CreatinganInstanceofanAutomationServer

Referencing a type library allows 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,whichactsastheprimaryobjectintheExcelobject

model. In fact, most Office programs have an Application

object. How do you know what objects an automation server

supports?Theonlysurewayistoconsultthedocumentationof

theprograminquestionorusetheObjectBrowserdiscussedin

Hour3,"UnderstandingObjectsandCollections."



In this example, you'll be using about a half-dozen

membersofanExcelobject.Thisdoesn'tevenbeginto

scratchthesurfaceofExcel'sobjectmodel,anditisn't

intendedto.Whatyoushouldlearnfromthisexample

isthemechanicsofworkingwithanautomationserver.

If you choose to automate a program in your own

projects, you'll want to consult the program's

developer documentation to learn about its object

model;you'resuretobesurprisedatthefunctionality

availabletoyou.

Double-clickthebuttontoaccessitsClickevent,andthenenter

thefollowingcode,whichcreatesanewExcelApplication:



Excel.ApplicationobjExcel=newExcel.Application();

Notice that C# included Excel in its IntelliSense drop-down list



of available objects. It was able to do this because you

referenced Excel's type library. Excel is the reference to the

serverandApplicationisanobjectsupportedbytheserver.This

statementcreatesanewApplicationobjectbasedontheExcel

objectmodel.







Top











ManipulatingtheServer

After you have an instance of an object from an automation

server, manipulating the server (creating objects, setting

properties, calling methods, and so forth) is accomplished by

manipulatingtheobject.



ForcingExceltoShowItself

When Excel is started using Automation, it's loaded but not

shown. By remaining hidden, it allows the developer to use its

functionalityandthencloseExcelwithouttheusereverknowing

what happened. For instance, you could create an instance of

an Excel object, perform a complicated formula to obtain a

result,closeExcel,andreturntheresulttotheuser—allwithout

the user ever seeing Excel. In this example, you want to see

Excelsothatyoucanseewhatyourcodeisdoing.Fortunately,

showingExcelcouldn'tbeeasier.Addthefollowingstatementto

makeExcelvisible:



objExcel.Visible=true;



CreatinganExcelWorkbookandWorksheet

In Excel, a Workbook is the file in which you work and store

your data; you can't manipulate data without a Workbook.

When you first start Excel from the Start menu, an empty

Workbookiscreatedforyou.However,whenyoustartExcelvia

Automation,Exceldoesn'tcreateaWorkbook;youhavetodoit

yourself.TocreateanewWorkbook,youusetheAddmethodof



theWorkbookscollection.AftertheWorkbookhasbeencreated,

you need to set up a worksheet. Enter the following

statements:



//startanewworkbookandaworksheet.

Excel.WorkbookobjBook=

objExcel.Workbooks.Add(System.Reflec

Excel.WorksheetobjSheet=(Excel.Worksheet)objBook.Wor

Notice

how

System.Reflection.Missing.Value is being

passed into the Add() method. This is because the

Add() method supports a default parameter and C#

does not support default parameters. Using the

System.Reflection.Missing.Value as the

parameter in the Add() method enables the COM's

late-binding service to use the default value for the

indicatedparametervalue.



WorkingwithDatainanExcelWorkbook

In this section, you're going to manipulate data in the

worksheet.Thefollowingdescribeswhatyou'lldo:

1. Adddatatofourcellsintheworksheet.

Selectthefourcells.

Totaltheselectedcellsandplacethesumintoafifthcell.

Boldallfivecells.

Tomanipulatecellsintheworksheet,youmanipulatetheRange



object, which is an object property of the Worksheet object.

Entering data into a cell involves first selecting a cell and then

passingdatatoit.Selectingacellisaccomplishedbysettinga

range object by calling the get_Range () method of the

Worksheet object; the get_Range () method is used to select

oneormorecells.Theget_Range()methodacceptsastarting

columnandrowandanendingcolumnandrow.Ifyouwantto

selectonlyasinglecell,aswedohere,youcansubstitutethe

ending

column

and

row

with

System.Reflection.Missing.Value parameter. After a

range is set, you pass data to the selected range by using the

set_Value() method on the Range object. Sound confusing?

Well, it is to some extent. Programs that support Automation

are often vast and complex, and programming them is usually

farfromintuitive.



range.set_Value(Missing.Value,"75") is

usedforExcel10(ExcelXP).Userange.Value=

"75"forExcel9(Excel2000).



If the program you want to automate has a macro

builder(asmostMicrosoftproductsdo),youcansave

yourselfalotoftimeandheadachebycreatingmacros

of the tasks you want to automate. The "macros" are

actually code, and in the case of Microsoft products,

they'reVBAcode.

Thefollowingsectionofcodeusesthetechniquesjustdescribed

toadddatatofourcells.Enterthiscodeintoyourprocedure:



Excel.RangeobjRange;



objRange=objSheet.get_Range("A1",System.Reflection.M



//ForEXCEL9UseobjRange.Valuemethodinplaceofall

//objRange.set_Value()statementsusedinthisexample

//objRange.Value="75";



objRange.set_Value(System.Reflection.Missing.Value,75



objRange=objSheet.get_Range("B1",System.Reflection.M

objRange.set_Value(System.Reflection.Missing.Value,125



objRange=objSheet.get_Range("C1",System.Reflection.M

objRange.set_Value(System.Reflection.Missing.Value,255



objRange=objSheet.get_Range("D1",System.Reflection.M

objRange.set_Value(System.Reflection.Missing.Value,295

ThenextstepistohaveExceltotalthefourcells.You'lldothis

byusingtheget_Range()methodtoselectthecellinwhichto

place the total, and then use set_Value() method again to

create the total by passing it a formula, rather than a literal

value.Enterthefollowingcodeintoyourprocedure:



objRange=objSheet.get_Range("E1",System.Reflection.M

objRange.set_Value(System.Reflection.Missing.Value,"=S

Next, you'll select all five cells and bold them. Enter the

followingstatementstoaccomplishthis:



objRange=objSheet.get_Range("A1","E1");

objRange.Font.Bold=true;

Thelastthingyouneedtodoisdestroytheobjectreferenceby

setting the object variable to null. Excel will remain open even

though you've destroyed the Automation instance (not all



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Hour 20. Controlling Other Applications Using Automation

Tải bản đầy đủ ngay(0 tr)

×