ExcelHome技术论坛

 找回密码
 免费注册

QQ登录

只需一步,快速开始

快捷登录

搜索
EH技术汇-专业的职场技能充电站 妙哉!函数段子手趣味讲函数 Excel服务器-会Excel,做管理系统 效率神器,一键搞定繁琐工作
HR薪酬管理数字化实战 Excel 2021函数公式学习大典 Excel数据透视表实战秘技 打造核心竞争力的职场宝典
让更多数据处理,一键完成 数据工作者的案头书 免费直播课集锦 ExcelHome出品 - VBA代码宝免费下载
用ChatGPT与VBA一键搞定Excel WPS表格从入门到精通 Excel VBA经典代码实践指南
查看: 7993|回复: 4

VBA与C#的交互----在Office中建立Com加载项(程序级)

[复制链接]

TA的精华主题

TA的得分主题

发表于 2012-11-16 11:00 | 显示全部楼层 |阅读模式
本帖已被收录到知识树中,索引项:VSTO开发
本帖最后由 liucqa 于 2012-11-19 15:12 编辑

http://support.microsoft.com/kb/302901/zh-cn

参考此贴,俺写出了第一个可以在Excel和Word自动加载的COM加载项。完全抄袭,给后来者做个样本。

MyCOMAddin.rar (30.57 KB, 下载次数: 269)

  1. namespace MyCOMAddin
  2. {
  3.     using System;
  4.     using Extensibility;
  5.     using System.Runtime.InteropServices;
  6.     //添加
  7.     using System.Reflection;
  8.     using Microsoft.Office.Core;

  9.     #region Read me for Add-in installation and setup information.
  10.     // When run, the Add-in wizard prepared the registry for the Add-in.
  11.     // At a later time, if the Add-in becomes unavailable for reasons such as:
  12.     //   1) You moved this project to a computer other than which is was originally created on.
  13.     //   2) You chose 'Yes' when presented with a message asking if you wish to remove the Add-in.
  14.     //   3) Registry corruption.
  15.     // you will need to re-register the Add-in by building the MyCOMAddinSetup project,
  16.     // right click the project in the Solution Explorer, then choose install.
  17.     #endregion
  18.    
  19.      
  20.     /// <summary>
  21.     ///   The object for implementing an Add-in.
  22.     /// </summary>
  23.     /// <seealso class='IDTExtensibility2' />
  24.     [GuidAttribute("9A742429-DAD4-4CE0-BA31-5CEB2E5B9813"), ProgId("MyCOMAddin.Connect")]
  25.     public class Connect : Object, Extensibility.IDTExtensibility2
  26.     {
  27.         
  28.         /// <summary>
  29.         ///        Implements the constructor for the Add-in object.
  30.         ///        Place your initialization code within this method.
  31.         /// </summary>
  32.         public Connect()
  33.         {
  34.         }

  35.         /// <summary>
  36.         ///      Implements the OnConnection method of the IDTExtensibility2 interface.
  37.         ///      Receives notification that the Add-in is being loaded.
  38.         /// </summary>
  39.         /// <param term='application'>
  40.         ///      Root object of the host application.
  41.         /// </param>
  42.         /// <param term='connectMode'>
  43.         ///      Describes how the Add-in is being loaded.
  44.         /// </param>
  45.         /// <param term='addInInst'>
  46.         ///      Object representing this Add-in.
  47.         /// </param>
  48.         /// <seealso class='IDTExtensibility2' />
  49.         public void OnConnection(object application, Extensibility.ext_ConnectMode connectMode, object addInInst, ref System.Array custom)
  50.         {
  51.             applicationObject = application;
  52.             addInInstance = addInInst;

  53.             //添加
  54.             if (connectMode != Extensibility.ext_ConnectMode.ext_cm_Startup)
  55.             {
  56.                 OnStartupComplete(ref custom);
  57.             }
  58.         }

  59.         /// <summary>
  60.         ///     Implements the OnDisconnection method of the IDTExtensibility2 interface.
  61.         ///     Receives notification that the Add-in is being unloaded.
  62.         /// </summary>
  63.         /// <param term='disconnectMode'>
  64.         ///      Describes how the Add-in is being unloaded.
  65.         /// </param>
  66.         /// <param term='custom'>
  67.         ///      Array of parameters that are host application specific.
  68.         /// </param>
  69.         /// <seealso class='IDTExtensibility2' />
  70.         public void OnDisconnection(Extensibility.ext_DisconnectMode disconnectMode, ref System.Array custom)
  71.         {
  72.             if (disconnectMode != Extensibility.ext_DisconnectMode.ext_dm_HostShutdown)
  73.             {
  74.                 OnBeginShutdown(ref custom);
  75.             }
  76.             applicationObject = null;
  77.         }

  78.         /// <summary>
  79.         ///      Implements the OnAddInsUpdate method of the IDTExtensibility2 interface.
  80.         ///      Receives notification that the collection of Add-ins has changed.
  81.         /// </summary>
  82.         /// <param term='custom'>
  83.         ///      Array of parameters that are host application specific.
  84.         /// </param>
  85.         /// <seealso class='IDTExtensibility2' />
  86.         public void OnAddInsUpdate(ref System.Array custom)
  87.         {
  88.         }

  89.         /// <summary>
  90.         ///      Implements the OnStartupComplete method of the IDTExtensibility2 interface.
  91.         ///      Receives notification that the host application has completed loading.
  92.         /// </summary>
  93.         /// <param term='custom'>
  94.         ///      Array of parameters that are host application specific.
  95.         /// </param>
  96.         /// <seealso class='IDTExtensibility2' />
  97.         public void OnStartupComplete(ref System.Array custom)
  98.         {
  99.             CommandBars oCommandBars;
  100.             CommandBar oStandardBar;
  101.             try
  102.             {
  103.                 oCommandBars = (CommandBars)applicationObject.GetType().InvokeMember("CommandBars", BindingFlags.GetProperty, null, applicationObject, null);
  104.             }
  105.             catch (Exception)
  106.             {
  107.                 // Outlook has the CommandBars collection on the Explorer object.
  108.                 object oActiveExplorer;
  109.                 oActiveExplorer = applicationObject.GetType().InvokeMember("ActiveExplorer", BindingFlags.GetProperty, null, applicationObject, null);
  110.                 oCommandBars = (CommandBars)oActiveExplorer.GetType().InvokeMember("CommandBars", BindingFlags.GetProperty, null, oActiveExplorer, null);
  111.             }

  112.             // Set up a custom button on the "Standard" commandbar.
  113.             try
  114.             {
  115.                 oStandardBar = oCommandBars["Standard"];
  116.             }
  117.             catch (Exception)
  118.             {
  119.                 // Access names its main toolbar Database.
  120.                 oStandardBar = oCommandBars["Database"];
  121.             }

  122.             // In case the button was not deleted, use the exiting one.
  123.             try
  124.             {
  125.                 MyButton = (CommandBarButton)oStandardBar.Controls["My Custom Button"];
  126.             }
  127.             catch (Exception)
  128.             {
  129.                 object omissing = System.Reflection.Missing.Value;
  130.                 MyButton = (CommandBarButton)oStandardBar.Controls.Add(1, omissing, omissing, omissing, omissing);
  131.                 MyButton.Caption = "My Custom Button";
  132.                 MyButton.Style = MsoButtonStyle.msoButtonCaption;
  133.             }
  134.             // The following items are optional, but recommended.
  135.             //The Tag property lets you quickly find the control
  136.             //and helps MSO keep track of it when more than
  137.             //one application window is visible. The property is required
  138.             //by some Office applications and should be provided.
  139.             MyButton.Tag = "My Custom Button";

  140.             // The OnAction property is optional but recommended.
  141.             //It should be set to the ProgID of the add-in, so that if
  142.             //the add-in is not loaded when a user presses the button,
  143.             //MSO loads the add-in automatically and then raises
  144.             //the Click event for the add-in to handle.
  145.             MyButton.OnAction = "!<MyCOMAddin.Connect>";

  146.             MyButton.Visible = true;
  147.             MyButton.Click += new Microsoft.Office.Core._CommandBarButtonEvents_ClickEventHandler(this.MyButton_Click);


  148.             object oName = applicationObject.GetType().InvokeMember("Name", BindingFlags.GetProperty, null, applicationObject, null);

  149.             // Display a simple message to show which application you started in.
  150.             System.Windows.Forms.MessageBox.Show("This Addin is loaded by " + oName.ToString(), "MyCOMAddin");
  151.             oStandardBar = null;
  152.             oCommandBars = null;
  153.         }

  154.         /// <summary>
  155.         ///      Implements the OnBeginShutdown method of the IDTExtensibility2 interface.
  156.         ///      Receives notification that the host application is being unloaded.
  157.         /// </summary>
  158.         /// <param term='custom'>
  159.         ///      Array of parameters that are host application specific.
  160.         /// </param>
  161.         /// <seealso class='IDTExtensibility2' />
  162.         public void OnBeginShutdown(ref System.Array custom)
  163.         {
  164.             object omissing = System.Reflection.Missing.Value;
  165.             System.Windows.Forms.MessageBox.Show("MyCOMAddin Add-in is unloading.");
  166.             MyButton.Delete(omissing);
  167.             MyButton = null;
  168.         }
  169.         private void MyButton_Click(CommandBarButton cmdBarbutton, ref bool cancel)
  170.         {
  171.             System.Windows.Forms.MessageBox.Show("MyButton was Clicked", "MyCOMAddin");
  172.         }
  173.         private object applicationObject;
  174.         private object addInInstance;
  175.         //添加
  176.         private CommandBarButton MyButton;
  177.     }
  178. }
复制代码



TA的精华主题

TA的得分主题

 楼主| 发表于 2012-11-16 11:40 | 显示全部楼层
Release.rar (294.94 KB, 下载次数: 148)

VS2010生成的安装文件。安装之后,启动Excel2007或者Word2007可以看到加载项。其他版本未测试。
在控制面板中可以卸载。

总体来说,用VS2010做Office的COM加载项还是很容易的。

TA的精华主题

TA的得分主题

 楼主| 发表于 2012-11-16 11:46 | 显示全部楼层
本帖最后由 liucqa 于 2012-11-16 12:03 编辑

2.JPG

安装之后,在HKEY_CLASSES_ROOT的CLSID中可以找到一楼代码中的{9A742429-DAD4-4CE0-BA31-5CEB2E5B9813}键值,里面是具体信息。

1.JPG

在office的Excel和Word的Addins中,可以看到加入的COM加载项。

1.JPG 启动Excel
2.JPG 加载项
3.JPG 点击菜单
4.JPG 退出Excel

TA的精华主题

TA的得分主题

发表于 2012-11-16 11:55 | 显示全部楼层

TA的精华主题

TA的得分主题

发表于 2012-12-26 16:30 | 显示全部楼层
[广告] Excel易用宝 - 提升Excel的操作效率 · Excel / WPS表格插件       ★免费下载 ★       ★ 使用帮助
最近发现个这样的问题,用Microsoft.Office.Interop.Word.Application新建一个word,如果设置此word的visible为true,之前的加载项能显式,如果visible设置为false,再打开其他word文档加载项就不显式,请问大哥知道什么原因吗?
您需要登录后才可以回帖 登录 | 免费注册

本版积分规则

手机版|关于我们|联系我们|ExcelHome

GMT+8, 2024-12-23 04:33 , Processed in 0.034021 second(s), 12 queries , Gzip On, MemCache On.

Powered by Discuz! X3.4

© 1999-2023 Wooffice Inc.

沪公网安备 31011702000001号 沪ICP备11019229号-2

本论坛言论纯属发表者个人意见,任何违反国家相关法律的言论,本站将协助国家相关部门追究发言者责任!     本站特聘法律顾问:李志群律师

快速回复 返回顶部 返回列表