用C#写Office插件 (ZT)
前段时间写了个Word的插件,因为项目最终没有谈成,也就没有做完,不过好歹写了点基本代码,记在这里,也免得以后用的时候再浪费时间。用C#写Office活着VS的插件是不困难的,VS提供了向导,会生成一个基本的框架,然后可以使用Office的对象模型加入些工具条按钮什么的,用C#写这些东西很方便,特别是连接事件,比起以前用C++写,真的是方便了很多,这种方便性也使得实现一些复杂的功能变得比较愉快
懒得整理了,把主要的代码贴在这里,其他功能方面的东西和写普通的winform程序也没什么区别。看到一些大虾贴的代码都有语法着色的,偶不会,只好弄成灰的了,要是哪位大虾路过看到,也留个言指点一下在下怎么在blog里使代码有语法着色,小的先谢了。
修改: 根据BirdsHome的方法, 修改成有语法着色的了
using System;
using Microsoft.Office.Core;
using Extensibility;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace WordExtCS
{
#region Read me for Add-in installation and setup information.
// When run, the Add-in wizard prepared the registry for the Add-in.
// At a later time, if the Add-in becomes unavailable for reasons such as:
// 1) You moved this project to a computer other than which is was originally created on.
// 2) You chose 'Yes' when presented with a message asking if you wish to remove the Add-in.
// 3) Registry corruption.
// you will need to re-register the Add-in by building the MyAddin21Setup project
// by right clicking the project in the Solution Explorer, then choosing install.
#endregion
/// <summary>
/// The object for implementing an Add-in.
/// </summary>
/// <seealso class='IDTExtensibility2' />
[GuidAttribute("C1C829AE-FCEB-4640-BF88-FF6CF8712426"), ProgId("WordExtCS.Connect")]
public class Connect : Object, Extensibility.IDTExtensibility2
{
/// <summary>
/// Implements the constructor for the Add-in object.
/// Place your initialization code within this method.
/// </summary>
public Connect()
{
}
#region IDTExtensibility2 接口实现
/// <summary>
/// Implements the OnConnection method of the IDTExtensibility2 interface.
/// Receives notification that the Add-in is being loaded.
/// </summary>
/// <param term='application'>
/// Root object of the host application.
/// </param>
/// <param term='connectMode'>
/// Describes how the Add-in is being loaded.
/// </param>
/// <param term='addInInst'>
/// Object representing this Add-in.
/// </param>
/// <seealso class='IDTExtensibility2' />
public void OnConnection(object application, Extensibility.ext_ConnectMode connectMode, object addInInst, ref System.Array custom)
{
addInInstance = addInInst;
if (application is Word.Application)
{
wordApp = (Word.Application)application;
}
if(connectMode != Extensibility.ext_ConnectMode.ext_cm_Startup)
{
OnStartupComplete(ref custom);
}
}
/// <summary>
/// Implements the OnDisconnection method of the IDTExtensibility2 interface.
/// Receives notification that the Add-in is being unloaded.
/// </summary>
/// <param term='disconnectMode'>
/// Describes how the Add-in is being unloaded.
/// </param>
/// <param term='custom'>
/// Array of parameters that are host application specific.
/// </param>
/// <seealso class='IDTExtensibility2' />
public void OnDisconnection(Extensibility.ext_DisconnectMode disconnectMode, ref System.Array custom)
{
if(disconnectMode != Extensibility.ext_DisconnectMode.ext_dm_HostShutdown)
{
OnBeginShutdown(ref custom);
}
wordApp = null;
}
/// <summary>
/// Implements the OnAddInsUpdate method of the IDTExtensibility2 interface.
/// Receives notification that the collection of Add-ins has changed.
/// </summary>
/// <param term='custom'>
/// Array of parameters that are host application specific.
/// </param>
/// <seealso class='IDTExtensibility2' />
public void OnAddInsUpdate(ref System.Array custom)
{
}
/// <summary>
/// Implements the OnStartupComplete method of the IDTExtensibility2 interface.
/// Receives notification that the host application has completed loading.
/// </summary>
/// <param term='custom'>
/// Array of parameters that are host application specific.
/// </param>
/// <seealso class='IDTExtensibility2' />
public void OnStartupComplete(ref System.Array custom)
{
//添加定制工具条
try
{
string caption = "投标系统";
object missing = System.Reflection.Missing.Value;
//看看工具条是不是已经存在
try
{
toolBar = wordApp.CommandBars[caption];
}
catch (Exception)
{
//如果不存在,创建工具条
toolBar = (Microsoft.Office.Core.CommandBar)wordApp.CommandBars.Add(
caption, Microsoft.Office.Core.MsoBarPosition.msoBarTop, missing, false);
toolBar.Visible = true;
}
}
catch (Exception e)
{
MessageBox.Show("添加投标系统工具条失败,异常信息:" + e.Message, "Tender System");
}
//添加按钮
try
{
btnConnect = AddButton("连接", 186, new Microsoft.Office.Core._CommandBarButtonEvents_ClickEventHandler(connect_Click));
comboSearch = AddComboBox("查找内容", new Microsoft.Office.Core._CommandBarComboBoxEvents_ChangeEventHandler(search_Change));
btnSearch = AddButton("查找", 46, new Microsoft.Office.Core._CommandBarButtonEvents_ClickEventHandler(search_Click));
btnAdvanced = AddButton("高级", 162, new Microsoft.Office.Core._CommandBarButtonEvents_ClickEventHandler(advanced_Click));
}
catch (Exception)
{
MessageBox.Show("添加按钮失败");
}
UpdateUI();
}
/// <summary>
/// Implements the OnBeginShutdown method of the IDTExtensibility2 interface.
/// Receives notification that the host application is being unloaded.
/// </summary>
/// <param term='custom'>
/// Array of parameters that are host application specific.
/// </param>
/// <seealso class='IDTExtensibility2' />
public void OnBeginShutdown(ref System.Array custom)
{
//toolBar.Delete();
}
#endregion
#region 辅助函数
/// <summary>
/// 添加一个按钮,并指定点击处理函数
/// </summary>
Microsoft.Office.Core.CommandBarButton AddButton(
string caption, int faceID,
Microsoft.Office.Core._CommandBarButtonEvents_ClickEventHandler clickHandler)
{
object missing = System.Reflection.Missing.Value;
try
{
Microsoft.Office.Core.CommandBarButton button;
//看看按钮是否已经存在
try
{
button = (Microsoft.Office.Core.CommandBarButton)toolBar.Controls[caption];
}
catch
{
//如果不存在,创建按钮
button = (Microsoft.Office.Core.CommandBarButton)
toolBar.Controls.Add(Microsoft.Office.Core.MsoControlType.msoControlButton,
missing, missing, missing, missing);
}
button.Caption = caption;
button.Tag = caption;
button.OnAction = "!<WordExtCS.Connect>";
button.TooltipText = caption;
button.FaceId = faceID;
button.Click += clickHandler;
return button;
}
catch (Exception)
{
MessageBox.Show("Error adding button: " + caption, "Error");
return null;
}
}
/// <summary>
/// 添加一个下拉框,并指定点击处理函数
/// </summary>
Microsoft.Office.Core.CommandBarComboBox AddComboBox(
string caption,
Microsoft.Office.Core._CommandBarComboBoxEvents_ChangeEventHandler comboHandler)
{
object missing = System.Reflection.Missing.Value;
try
{
Microsoft.Office.Core.CommandBarComboBox combo;
//看看combo是否已经存在
try
{
combo = (Microsoft.Office.Core.CommandBarComboBox)toolBar.Controls[caption];
}
catch
{
//如果不存在,创建
combo = (Microsoft.Office.Core.CommandBarComboBox)
toolBar.Controls.Add(Microsoft.Office.Core.MsoControlType.msoControlComboBox,
missing, missing, missing, missing);
}
combo.Caption = caption;
combo.Tag = caption;
combo.TooltipText = caption;
combo.OnAction = "!<WordExtCS.Connect>";
combo.Change += comboHandler;
return combo;
}
catch (Exception)
{
MessageBox.Show("Error adding combo: " + caption, "Error");
return null;
}
}
/// <summary>
/// 根据当前状态更新工具条界面
/// </summary>
private void UpdateUI()
{
if (connected)
{
btnConnect.TooltipText = "断开";
btnConnect.FaceId = 184;
comboSearch.Enabled = true;
btnSearch.Enabled = true;
btnAdvanced.Enabled = true;
}
else
{
btnConnect.TooltipText = "连接";
btnConnect.FaceId = 186;
comboSearch.Enabled = false;
btnSearch.Enabled = false;
btnAdvanced.Enabled = false;
}
}
#endregion
#region 事件处理函数
/// <summary>
/// 连接按钮相应函数
/// </summary>
public void connect_Click(Microsoft.Office.Core.CommandBarButton btn, ref bool someBool)
{
if (!connected)
{
//建立连接
using (LoginForm dlg = new LoginForm())
{
if (dlg.ShowDialog()==DialogResult.OK)
{
//...
connected = true;
}
}
}
else
{
//断开连接
connected = false;
}
UpdateUI();
}
public void search_Change(Microsoft.Office.Core.CommandBarComboBox combo)
{
combo.AddItem(combo.Text, 0);
//wordApp.ActiveWindow.Selection.InsertBefore(combo.Text);
}
public void search_Click(Microsoft.Office.Core.CommandBarButton btn, ref bool someBool)
{
using (SearchResult resultForm = new SearchResult())
{
if (resultForm.ShowDialog() == DialogResult.OK)
{
}
}
}
public void advanced_Click(Microsoft.Office.Core.CommandBarButton btn, ref bool someBool)
{
mainForm.ShowDialog();
}
#endregion
//private object applicationObject;
private Word.Application wordApp;
private Microsoft.Office.Core.CommandBar toolBar;
private Microsoft.Office.Core.CommandBarButton btnConnect;
private Microsoft.Office.Core.CommandBarButton btnSearch;
private Microsoft.Office.Core.CommandBarComboBox comboSearch;
private Microsoft.Office.Core.CommandBarButton btnAdvanced;
private object addInInstance;
private bool connected = false;
private TenderMain mainForm = new TenderMain();
}
}