VSTO外接程序项目只用1个文件实现Ribbon CustomUI和CustomTaskpane定制【C#版】
VSTO中的自定义功能区和自定义任务窗格需要用到各种命名空间、添加所需文件,才能实现。后来我发现可以把所有代码都写在ThisAddin.cs这个默认文件中。
大家可以在Visual Studio中创建一个外接程序项目,然后把ThisAddin.cs中的代码整体替换为下面我贴的这个代码。然后启动调试,就可以看到自定义功能区和任务窗格了。
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Xml.Linq; 6 using Excel = Microsoft.Office.Interop.Excel; 7 using Office = Microsoft.Office.Core; 8 using Microsoft.Office.Tools.Excel; 9 10 namespace ExcelAddInTemplate_CS 11 { 12 public partial class ThisAddIn 13 { 14 private void ThisAddIn_Startup(object sender, System.EventArgs e) 15 { 16 Module1.CreateCTP(); 17 } 18 19 private void ThisAddIn_Shutdown(object sender, System.EventArgs e) 20 { 21 Module1.DisposeCTP(); 22 } 23 protected override Office.IRibbonExtensibility CreateRibbonExtensibilityObject() 24 { 25 return new Ribbon1(); 26 } 27 #region VSTO generated code 28 29 /// <summary> 30 /// Required method for Designer support - do not modify 31 /// the contents of this method with the code editor. 32 /// </summary> 33 private void InternalStartup() 34 { 35 this.Startup += new System.EventHandler(ThisAddIn_Startup); 36 this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown); 37 } 38 39 #endregion 40 } 41 [System.Runtime.InteropServices.ComVisible(true)] 42 public class Ribbon1:Microsoft.Office.Core.IRibbonExtensibility 43 { 44 public Office.IRibbonUI R; 45 string Office.IRibbonExtensibility.GetCustomUI(string RibbonID) 46 { 47 string xml= @"<customUI xmlns='http://schemas.microsoft.com/office/2009/07/customui' onLoad='OnLoad'> 48 <ribbon startFromScratch='false'> 49 <tabs> 50 <tab id='Tab1' label='RibbonXmlEditor'> 51 <group id='Group1' label='Author:ryueifu'> 52 <button id='Button1' label='CTP' imageMso='C' onAction='Button1_Click'/> 53 <button id='Button2' label='UnLoad' imageMso='U' onAction='Button2_Click'/> 54 </group> 55 </tab> 56 </tabs> 57 </ribbon> 58 </customUI>"; 59 return xml; 60 } 61 public void OnLoad(Office.IRibbonUI ribbon) 62 { 63 R = ribbon; 64 R.ActivateTab(ControlID: "Tab1"); 65 } 66 public void Button1_Click(Office.IRibbonControl control) 67 { 68 Module1.ctp.Visible = !Module1.ctp.Visible; 69 } 70 public void Button2_Click(Office.IRibbonControl control) 71 { 72 Office.COMAddIn ThisCOM = Globals.ThisAddIn.Application.COMAddIns.Item("ExcelAddInTemplate_CS"); 73 ThisCOM.Connect = false; 74 } 75 76 } 77 public static class Module1 78 { 79 public static System.Windows.Forms.UserControl uc; 80 public static Microsoft.Office.Tools.CustomTaskPane ctp; 81 public static void CreateCTP() 82 { 83 uc = new System.Windows.Forms.UserControl(); 84 ctp = Globals.ThisAddIn.CustomTaskPanes.Add(control: uc, title: "CTP"); 85 ctp.DockPosition = Office.MsoCTPDockPosition.msoCTPDockPositionRight; 86 ctp.Visible = true; 87 } 88 public static void DisposeCTP() 89 { 90 ctp.Dispose(); 91 } 92 } 93 }