How to: Use Visual C #. Net to generate an office com external program

Source: Internet
Author: User
Tags microsoft outlook
Go to http://support.microsoft.com/kb/302901/zh-cnoverview

Both Microsoft Office XP and Microsoft Office 2003 support a new unified design structure used to generate applicationsProgramAdd-on programs to enhance and Control Office applications. These external programs are called com external programs. This article gradually discusses the Office com external program and describes how to use Microsoft Visual C #. Net to generate an office com external program.

Back to Top

Idtexensibility2 Interface

A com external program is a COM server or ActiveX dynamic link library (DLL) in the process. It is implemented as described in the Microsoft external program designer Type Library (msaddndr. dll ).Idtexensibility2Interface. All com external programs inherit from this interface, and each of the five methods must be implemented.

Onconnection

Each time a com external program is connectedOnconnectionEvent. The external program can be connected at startup, By the end user, or through automation. IfOnconnectionIf the response is successful, the external program has been loaded. If an error message is returned, the host application immediately releases its reference to the external program, and the object will be destroyed.

OnconnectionUse the following four parameters:

Application-A reference to the Host application object.
Connectmode-A constant that specifies the connection mode of an external program. An external program can be connected in the following ways:

Ext_cm_afterstartup-The external program starts from the End UserCom external programThe dialog box is started.
Ext_cm_commandline-The external program is connected from the command line. Note: This method is not applicable to com external programs that generate office applications.
Ext_cm_external-The external program is automatically connected by the external application. Note that this method is not applicable to com external programs that generate office applications.
Ext_cm_startup-The external program is started by the host when the application starts. This row is controlled by settings in the registry.
Addininst-A PairComaddinObject, which referencesComaddinsOther programs in the set.
Custom-One includeVariantType value array, which can store user-defined data.
Ondisconnection

When the com external program is disconnected and before it is detached from the memoryOndisconnectionEvent. The external program should clean up all resources in this event and restore any changes made to the Host application.

OndisconnectionUse the following two parameters:

Removemode-A constant that specifies the method in which the external program is disconnected. You can disconnect an external program in the following ways:

Ext_dm_hostshutdown-The external program is disconnected when the host application is closed.
Ext_dm_userclosed-The external program is disconnected from the end user or the automation controller.
Custom-One includeVariantType value array, which can store user-defined data.
Onaddinsupdate

When the registered com external Assembly changesOnaddinsupdateEvent. In other words, this event is triggered whenever a com external program is installed or the com external program is deleted from the host application.

Onstartupcomplete and onbeginshutdown

When the host application is busy loading itself into the memory or detaching itself from the memory, user interaction should be avoided.OnstartupcompleteAndOnbeginshutdownMethods are called when the host application has left or is about to enter this state. It is called only when an external program is connected during startup.Onstartupcomplete, Called only when the host needs to disconnect from the external program during the Shutdown ProcessOnbeginshutdown.

Because the user interface of the Host application is fully active when these events are triggered, they may be the only way to execute some operations and will not be available fromOnconnectionAndOndisconnection.

Back to Top

Com external program Registration

In addition to normal com registration, the com external program also needs to register itself with each office application where it runs. To register itself with a specific application, the external program should use its progid as the item name to create a subitem in the following locations:

HKEY_CURRENT_USER \ Software \ Microsoft \ Office \Officeapp\ Addins \Progid

The external program can provide a value for the displayed name and complete description. In addition, the external program should use a DWORD Value named loadbehavior to specify the desired loading behavior. This value determines how the Host application loads the external program and consists of a combination of the following values:

0 = disconnect-not loaded.
1 = connected-loaded.
2 = bootload-load when the application starts.
8 = demandload-load only when requested by the user.
16 = connectfirsttime-load only once (at next startup ).

Generally, the value 0x03 (connected | bootload) is specified.

ImplementedIdtextensibility2The external program should also specify a DWORD Value named commandlinesafe to indicate whether the external program is safe for operations that do not support the user interface. 0x00 indicates false, and 0x01 indicates true.

Back to Top

How to Use Visual C #. Net to generate a com external program

As described above, the Office com external program is an in-process COM server activated by the Office application through the com runtime layer. Therefore, to develop com external programs in. net, the external program components must be implemented in. net, and then published to the COM Client (that is, the Office application) through the com InterOP layer.

To create a com external program in Visual C #. net, follow these steps:

1. in Visual C #. net, create a class library project.
2. Add a reference to the type library that implements idtextensibility2 . The main InterOP assembly of this item has already appeared under the extensibility name.
3. Add a reference to the Microsoft Office Object Library. The main InterOP assembly of this item has already appeared under the Office name.
4. create a public class in the idtextensibility2 class library.
5. after the class library is generated, register the library with COM InterOP. To do this, you need to generate an assembly with a strong name for this class library, and then register it to com InterOP. You can use regasm.exe to register the. NET component with COM InterOP.
6. create a registry entry so that office applications can recognize and load external programs.

You can select to complete all these steps, or you can createShared external program. Net project. This will start the "scalability wizard", which helps you create a com external program in. net.

The "scalability wizard" creates a Visual C #. Net class library project, and createsIdtextensibility2InterfaceConnectClass. It also generates an implementationIdtextensibilityThe backbone of the empty member.Code. This project has reference to extensibility and office assembly. The project generation settings are selected.Register com InterOP. The Assembly key (. SNK) file is generated, andAssemblykeyfileAttribute.

In addition to the class library project, the wizard also generates an installation project that can be used to deploy com external programs on other computers. You can delete this project as needed.

Back to Top

Step-by-step examples


1. In Microsoft Visual Studio. NETFileClickNewAnd then clickProject.
2. InCreate a projectDialog box, expandProject TypeUnderOther projects, SelectScalability ProjectAnd then selectShared external programTemplate.
3. TypeMycomaddinAs the name of the external program, and then clickOK.
4. After the scalability wizard appears, follow these steps:

A. On the 1st page, selectUse Visual C # to create an external programAnd then clickNext step.
B. On the 2nd page, select the following Host application, and then clickNext step:

Microsoft Word
Microsoft PowerPoint
Microsoft Outlook
Microsoft Excel
Microsoft Access
C. On the 3rd page, enter the name and description of the external program, and then clickNext step.

Note:: The name and description of the external program appear inCOM add-onDialog box.

D. On the 4th page, select all available options and clickNext step.
E. ClickComplete.
5. InProjectClickAdd reference. ClickSystem. Windows. Forms. dll, ClickSelectAnd then clickOK.
6. Add the following codeConnectIn the namespace list of the class:

Using system. reflection;

7. Add the following membersConnectClass:

Private commandbarbutton mybutton;

8. In Connect Class implementation Idtextensibility2 The code of the member is as follows:

Public void onconnection (object application, extensibility. ext_connectmode connectmode, object addininst, Ref system. array custom) {applicationobject = application; addininstance = addininst; If (connectmode! = Extensibility. ext_connectmode.ext_cm_startup) {onstartupcomplete (ref custom) ;}} public void ondisconnection (extensibility. ext_disconnectmode disconnectmode, Ref system. array custom) {If (disconnectmode! = Extensibility. ext_disconnectmode.ext_dm_hostshutdown) {onbeginshutdown (ref custom);} applicationobject = NULL;} public void onaddinsupdate (Ref system. array custom) {} public void onstartupcomplete (Ref system. array custom) {commandbars ocommandbars; commandbar ostandardbar; try {ocommandbars = (commandbars) applicationobject. getType (). invokemember ("commandbars", bindingflags. getproperty, NUL L, applicationobject, null);} catch (exception) {// outlook has the commandbars collection on the Explorer Object. object oactiveexplorer; oactiveexplorer = applicationobject. getType (). invokemember ("activeexplorer", bindingflags. getproperty, null, applicationobject, null); ocommandbars = (commandbars) oactiveexplorer. getType (). invokemember ("commandbars", bindingflags. getproperty, null, oactiveexplorer, null );} // Set up a Custom button on the "standard" commandbar. try {ostandardbar = ocommandbars ["standard"];} catch (exception) {// access names its main toolbar database. ostandardbar = ocommandbars ["Database"];} // In case the button was not deleted, use the exiting one. try {mybutton = (commandbarbutton) ostandardbar. controls ["My Custom button"];} catch (exception) {object omissing = system. R Eflection. missing. value; mybutton = (commandbarbutton) ostandardbar. controls. add (1, omissing, omissing); mybutton. caption = "My Custom button"; mybutton. style = msobuttonstyle. msobuttoncaption;} // The following items are optional, but recommended. // The tag property lets you quickly find the control // and helps MSO keep track of it when more than // One application window Is visible. the property is required // by some office applications and shoshould be provided. mybutton. tag = "My Custom button"; // The onaction property is optional but recommended. // It shoshould be set to the progid of the add-in, so that if // the add-in is not loaded when a user presses the button, // MSO loads the add-in automatically and then raises // The click event for the add-in to handle. mybut Ton. onaction = "! <Mycomaddin. connect> "; mybutton. visible = true; mybutton. click + = new Microsoft. office. core. _ commandbarbuttonevents_clickeventhandler (this. mybutton_click); object oname = applicationobject. getType (). invokemember ("name", bindingflags. getproperty, null, applicationobject, null); // display a simple message to show which application you started in. system. windows. forms. messageBox. show ("This Addin is loaded by" + oname. tostring (), "mycomaddin"); ostandardbar = NULL; ocommandbars = NULL;} public void onbeginshutdown (Ref system. array custom) {object omissing = system. reflection. missing. value; system. windows. forms. messageBox. show ("mycomaddin add-in is unloading. "); mybutton. delete (omissing); mybutton = NULL;} private void mybutton_click (commandbarbutton cmdbarbutton, ref bool cancel) {system. windows. forms. messageBox. show ("mybutton was clicked", "mycomaddin ");}

9. Generate and test the com external program. To do this, follow these steps:

A. On the Generate menu, click Generate solution . Note that the. Net class is actually registered with COM InterOP during the com external program generation process.
B. Start an office application (for example, Microsoft Word or Microsoft Excel) of the Host application you selected as the external program ).
C. after an external program is started, the onstartupcomplete event is triggered. You will receive a message box. Close the message box. Note that the external program adds a new Custom button named "My Custom button" (My Custom button) to the Standard toolbar.
D. click My Custom button . The click event of this button is handled by an external program, and you will receive a message box. Close the message box.
E. exit the Office application.
F. when you exit the application, the onbeginshutdown event is triggered. You will receive a message box. Close the message box to end the demo.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.