這篇博客將簡單介紹一些VSTO Addin開發的知識。
1. VSTO是什么?我們可以用VSTO做什么?
VSTO全稱Visual Studio Tool for Office,是可以讓我們針對現有的Office程序進行功能擴展。在工作或生活中其實我們或多或少用到過VSTO插件,例如安裝有道詞典/Adobe Pro會在Office程序中嵌入插件程序。
2. VSTO開發環境的准備:
(1). 我們的PC上需要安裝有Office(Office 2007及以上版本);
(2). 以Visual Studio 2015為例,在安裝時需要勾選Office Development模塊。如果初始安裝沒有安裝也沒關系,可以在控制面板中通過更改Visual Studio的方式進行安裝。成功安裝后,打開Visual Studio 2015-->新建工程-->選擇Office Development模塊:
3. Office 開發的模板,我們主要看(Application-Level/Template-Level)的模板,這兩者的加載方式請看下面的圖示:
打開Office解決方案的文檔后,Microsoft Office 應用程序檢查自定義文檔屬性,以確定是否有與文檔關聯的托管代碼擴展。
PS: 這兩者在開發上的區別就是模板不一樣,別的基本沒有。另外一個Application-Level是針對整個Office Word/Excel/...的定制,而Template-Level是正對Word/Excel/...模板的定制。
4. 我們以VSTO Word Addin為例,講一下VSTO Word Addin Development中的核心對象。
private void ThisAddIn_Startup(object sender, System.EventArgs e) { Application.WindowSelectionChange += Application_WindowSelectionChange; Word.Document doc = Globals.ThisAddIn.Application.Documents.Open(@"D:\demo.docx", AddToRecentFiles: false); } /// <summary> /// WindowsSelectionChange事件 /// </summary> /// <param name="Sel">選中文本</param> private void Application_WindowSelectionChange(Word.Selection Sel) { if (Sel.Range.End - Sel.Range.Start > 10) { Word.Range range = Sel.Range; System.Diagnostics.Debug.WriteLine("Range Start Position: {0} Range End Position: {1}", range.Start, range.End); range.Bookmarks.Add("MyBookmark"); } }
運行效果: 向Word的Bookmark中插入一個Bookmark:
當我們編譯Word Addin工程時,會向注冊表中寫入插件的一些信息,例如Description, FriendlyName, LoadBehavior, Mantifest等,此時當我們單獨打開Word時,插件還是會運行的。清理一下Visual Studio Word Addin工程即可。
5. 如何部署VSTO插件(以Word為例),從Visual Studio編譯Word插件時,向注冊表中寫入的信息,我們可以利用這些注冊表信息來部署Word插件,
