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

Source: Internet
Author: User
Tags microsoft outlook
Use Visual C #. Net to generate an office com external program

For the Microsoft Visual Basic. Net version in this article, see 302896. For Microsoft Visual Basic 6.0 in this article, see 238228. For Microsoft Visual C ++ 6.0 in this article, see section 230689.

Content of this task
  • Summary

    • Idtexensibility2 Interface
      • Onconnection
      • Ondisconnection
      • Onaddinsupdate
      • Onstartupcomplete and onbeginshutdown
    • Com external program Registration
    • How to Use Visual C #. Net to generate a com external program
    • Step-by-step examples
  • Reference

Summary

Both Microsoft Office XP and Microsoft Office 2003 support a new unified design structure that is used to generate application external 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.

Back to Top

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.

Back to Top

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.

Back to Top

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.

Back to Top

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 useLoadbehaviorDWORD Value of specifies 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.

ImplementedIdtextensibility2You should also specify an external program namedCommandlinesafeTo 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 pair to implementIdtextensibility2. The master InterOP assembly for this item already appears inExtensibilityName.
  3. Add a reference to the Microsoft Office Object Library. The master InterOP assembly for this item already appears inOfficeName.
  4. AfterIdtextensibility2To create a public class.
  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 applications.

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 code of the empty member. 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:
    1. On the 1st page, selectUse Visual C # to create an external programAnd then clickNext step.
    2. On the 2nd page, select the following Host application, and then clickNext step:
      • Microsoft Word
      • Microsoft PowerPoint
      • Microsoft Outlook
      • Microsoft Excel
      • Microsoft Access
    3. 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.

    4. On the 4th page, select all available options and clickNext step.
    5. 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. InConnectClass implementationIdtextensibility2The 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 , null, 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.Reflection.Missing.Value ;      MyButton = (CommandBarButton) oStandardBar.Controls.Add(1, omissing , omissing , 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 should be provided.   MyButton.Tag = "My Custom Button";   // The OnAction property is optional but recommended.    //It should 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.    MyButton.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:
    1. InGenerateClickGenerate a solution. Note that the. Net class is actually registered with COM InterOP during the com external program generation process.
    2. Start an office application (for example, Microsoft Word or Microsoft Excel) of the Host application you selected as an external program ).
    3. After the external program is startedOnstartupcompleteEvent, 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.
    4. ClickMy Custom button (My Custom button). TheClickThe event will be handled by an external program, and you will receive a message box. Close the message box.
    5. Exit the Office application.
    6. When you exit the applicationOnbeginshutdownEvent, you will receive a message box. Close the message box to end the demo.
Related Article

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.