1. 程式人生 > >VSTO外接程式專案只用1個檔案實現Ribbon CustomUI和CustomTaskpane定製【C#版】

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 }