前段时间有一个需求需要在一个Word文档中选定文字后在右键菜单中添加一个按钮点击后弹出一个WinForm窗体,由于在实际做的过程中
遇到了两个问题因此记录下来.具体做法如下:
  1. 在vs2005中新建一个 shared Add-in 项目,一步一步Next,到Select An Application Host的时候只钩选 Microsoft Word,然后一直Next到完成,会自动创建一个wordAddin项目并带安装项目.
  2. 在项目的Connect.cs中的OnConnection方法中添加代码,这个是启动入口,当Word打开的时候会自动调用这个方法.一下是代码:    public void OnConnection(object application, Extensibility.ext_ConnectMode connectMode, object addInInst, ref System.Array custom) { applicationObject = application; addInInstance = addInInst; Word.Application app = application as Word.Application; CreateContextMenu(app); }
  3. CreateContextMenu(app)方法,注意此处添加的CommandBarButton必须是全局的,不然其Click事件开始只会触发1~2次,后面将不会触发:
    private Office.CommandBarButton ShowButton; private static Office.CommandBarButton ShowTermButton; public static void CreateContextMenu(Word.ApplicationClass app) { Office.CommandBars commandBars = (Office.CommandBars)app.CommandBars; object missing = System.Reflection.Missing.Value; Office.CommandBar listsbar = commandBars["Lists"]; if (listsbar != null) { ShowButton = (Office.CommandBarButton)listsbar.FindControl(Office.MsoControlType.msoControlButton, missing, Constants.TestForViewParaphrase, true, true); if (ShowButton == null) ShowButton = (Office.CommandBarButton)listsbar.Controls.Add(Office.MsoControlType.msoControlButton, missing, missing, 1, missing); ShowButton.Caption = Constants.TestForViewParaphrase; ShowButton.Style = Microsoft.Office.Core.MsoButtonStyle.msoButtonCaption; ShowButton.Visible = true; ShowButton.Tag = Constants.TestForViewParaphrase; ShowButton.Click += new Microsoft.Office.Core._CommandBarButtonEvents_ClickEventHandler(ShowButton_Click); ShowTermButton = (Office.CommandBarButton)listsbar.FindControl(Office.MsoControlType.msoControlButton, missing, Constants.TextForAddTermNet, true, true); if (ShowTermButton == null) ShowTermButton = (Office.CommandBarButton)listsbar.Controls.Add(Office.MsoControlType.msoControlButton, missing, missing, 1, missing); ShowTermButton.Caption = Constants.TextForAddTermNet; ShowTermButton.Style = Microsoft.Office.Core.MsoButtonStyle.msoButtonCaption; ShowTermButton.Visible = true; ShowTermButton.Tag = Constants.TextForAddTermNet; ShowTermButton.Click += new Microsoft.Office.Core._CommandBarButtonEvents_ClickEventHandler(ShowTermButton_Click); } }
  4. 在ShowTermButton_Click事件中将显示一个Form,这里要做特殊处理,就是如何使弹出的窗体自动置于打开的Word之上,在网上找了很久才找到可行的处理方式,是参照http://social.msdn.microsoft.com/forums/en-US/vsto/thread/19539460-14ce-4ea0-9a53-50d38a4eb3b0/ 这个地方来的,代码如下:
    void ShowTermButton_Click(Microsoft.Office.Core.CommandBarButton Ctrl, ref bool CancelDefault) { try { Word.Range range = appClass.ActiveWindow.Selection.Range; if (string.IsNullOrEmpty(range.Text)) return; Form form= new Form(); form.ShowDialog(new WordWin32Window(appClass)); form.Dispose(); } } catch (Exception ex) { Log.Error("Show Form error" + ex); } }

    WordWin32Window类代码如下:
    /// /// Word example code by H.Obertanner http://www.outlooksharp.de /// Created 2008 with Office 2007 and VSTO 3.0 /// Free for non commercial use. using System; using System.Windows.Forms; using System.Runtime.InteropServices; using System.Collections.Generic; using System.Threading; using System.Reflection; using System.Diagnostics; using System.Text; namespace CO.WordLib { /// <summary> /// This class retrieves the IWin32Window from the current active Word window. /// This could be used to set the parent for Windows Forms and MessageBoxes. /// </summary> /// <example> /// WordWin32Window parentWindow = new WordWin32Window (ThisAddIn.WordApplication); /// MessageBox.Show (parentWindow, "This MessageBox doesn't go behind Word !!!", "Attention !", MessageBoxButtons.Ok , MessageBoxIcon.Question ); /// </example> public class WordWin32Window : IWin32Window { /// <summary> /// Returns a Handle to the Desktop-Window /// </summary> /// <returns>The handle</returns> [DllImport("user32")] private static extern IntPtr GetDesktopWindow(); /// <summary> /// Finds a Window-Handle by its name or classname /// </summary> /// <param name="hwndParent">The Parent Windows-Handle</param> /// <param name="hwndChildAfter">Start the search after the given Windows-Handle</param> /// <param name="lpszClass">The classname to search for</param> /// <param name="lpszWindow">The window caption to search for</param> /// <returns><returns the windows-Handle or IntPtr.Zero</returns> [DllImport("user32")] private static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow); /// <summary> /// Gets the title of a Window. /// </summary> /// <param name="hWnd">The Windows Handle.</param> /// <param name="lpString">A pointer to a StringBuilder-Object.</param> /// <param name="nMaxCount">Max num of chars to get.</param> [DllImport("user32", CharSet = CharSet.Auto)] private static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount); #region IWin32Window Members /// <summary> /// This holds the window handle for the found Window. /// </summary> IntPtr _windowHandle = IntPtr.Zero; /// <summary> /// The <b>Handle</b> of the Word WindowObject. /// </summary> public IntPtr Handle { get { return _windowHandle; } } #endregion /// <summary> /// The <b>WordWin32Window</b> class could be used to get the parent IWin32Window for Windows.Forms and MessageBoxes. /// </summary> /// <param name="wordApp">The Word ApplicationObject.</param> public WordWin32Window(object wordApp) { // how to find my Word Windows-Handle... string oldCaption = (string)wordApp.GetType().InvokeMember("Caption", BindingFlags.GetProperty, null, wordApp, null); // unique identifier string newCaption = Guid.NewGuid().ToString(); // set a new caption to the Word Window wordApp.GetType().InvokeMember("Caption", BindingFlags.SetProperty, null, wordApp, new object[] { newCaption }); // get the Desktop WindowHandle IntPtr hDesktop = GetDesktopWindow(); // Find all Word Windows-Handles // Find the first instance IntPtr hWnd = FindWindowEx(hDesktop, IntPtr.Zero, "OpusApp", null); StringBuilder windowText = new StringBuilder(255); while (hWnd != IntPtr.Zero) { // Get the window-caption GetWindowText(hWnd, windowText, 255); if (windowText.ToString().EndsWith(newCaption)) { // gotcha _windowHandle = hWnd; break; } // Next - starting after the last found window hWnd = FindWindowEx(hDesktop, hWnd, "OpusApp", null); } // Reset the caption wordApp.GetType().InvokeMember("Caption", BindingFlags.PutDispProperty, null, wordApp, new object[] { oldCaption }); } } }

  5. 另一个按钮事件,显示气泡:
    void ShowButton_Click(Microsoft.Office.Core.CommandBarButton Ctrl, ref bool CancelDefault) { try { Office.Balloon balloon = appClass.Assistant.NewBalloon; balloon.BalloonType = Office.MsoBalloonType.msoBalloonTypeNumbers; balloon.Button = Office.MsoButtonSetType.msoButtonSetOK; balloon.Heading = "View Text"; balloon.Text = appClass.ActiveWindow.Selection.Text; balloon.Show(); } catch (Exception ex) { } }

在Word中创建CommandBar并显示winform窗体相关推荐

  1. 微软word开机自启动_如何在Microsoft Word中创建自定义封面

    微软word开机自启动 A great cover page draws in readers. If you use Microsoft Word, you're in luck, because ...

  2. c# 获取word表格中的内容_Java 在Word中创建嵌套表格

    嵌套表格,即在一个大的表格单元格中再嵌进去一个或几个小的表格,使表格内容布局合理.本文将通过java程序来演示如何在Word中创建嵌套表格. 使用工具:Free Spire.Doc for Java ...

  3. Java学习笔记:Word中创建图表如此简单

    用法 Word中创建图表的方式是一样的. XWPFChart chart = WordHelpers.createChart(doc,500,300); XWPFChart和XSSFChart一样都是 ...

  4. Microsoft Word教程:如何在 Word 中创建文档、添加和编辑文本?

    欢迎观看 Microsoft Word 教程,小编带大家学习 Microsoft Word 的使用技巧,了解如何在 Word 中创建文档.添加和编辑文本. 创建文档,打开 Word,选择「空白文档」. ...

  5. word中创建文本框

    word中创建文本框         在插入中点击"文本框"选项卡,如下图所示:        手工添加自己想要的文本框格式,然后选择所创建的文本框,在工具栏处会发现多了一个&qu ...

  6. Word控件Spire.Doc 【Table】教程(1):在 Word 中创建表格-C#VB.NET

    Spire.Doc for .NET是一款专门对 Word 文档进行操作的 .NET 类库.在于帮助开发人员无需安装 Microsoft Word情况下,轻松快捷高效地创建.编辑.转换和打印 Micr ...

  7. python生成word文档的表格_说说如何使用 Python 在 word 中创建表格

    我们可以使用 python-docx 模块,实现在 word 中创建表格. 请看下面这段代码: table = doc.add_table(rows=1, cols=len(titles)) # 设置 ...

  8. 如何通过Java代码在Word中创建可填充表单

    有时候,我们需要制作一个Word模板文档,然后发给用户填写,但我们希望用户只能在指定位置填写内容,其他内容不允许编辑和修改.这时候我们就可以通过表单控件来轻松实现这一功能.本文将为您介绍如何通过Jav ...

  9. Microsoft Word教程「1」,如何在 Word 中创建文档、添加和编辑文本?

    欢迎观看 Microsoft Word 教程,小编带大家学习 Microsoft Word 的使用技巧,了解如何在 Word 中创建文档.添加和编辑文本. 创建文档,打开 Word,选择「空白文档」. ...

最新文章

  1. java biginteger使用_java中的BigInteger的基本用法 | 学步园
  2. java中获取文件总行数_关于java:如何以有效的方式获取文件中的行数?
  3. Android UI事件处理
  4. Dubbo -- 系统学习 笔记 -- 示例 -- 服务分组
  5. 在ASP.NET Core 2.2 Web应用程序项目中自定义Bootstrap
  6. 【软考】面向对象程序设计复习指南
  7. 反编译exe软件_挖洞经验 | Panda反病毒软件本地提权漏洞分析
  8. javascript:js+css实现加载特效
  9. 利用python爬虫程序爬取豆瓣影评
  10. 前端开发找实习宝贵经验总结
  11. 题解【[FJOI2018]所罗门王的宝藏】
  12. 【MySQL学习笔记】电子杂志订阅表的操作
  13. 『互联网架构』软件架构-深入理解Ribbon
  14. 国际音标(IPA)和美国音标(KK)对照表
  15. Git基本操作和GtHub 特殊技巧
  16. C# Timer详解
  17. 计算机 计算能力测试题,高中数学计算能力训练题.doc
  18. 面试后说hold什么意思_面试快结束时,如果面试官对你说这几句话,说明你被淘汰了!...
  19. 简单到出人意料的CNN图像分类策略
  20. java中的push方法_Java ArrayDeque push()方法与示例

热门文章

  1. 403 (forbidden)
  2. 用C++ 实现(程序自杀)
  3. VideoEdit Gold ActiveX 控件,生成ActiveX控制函数的方法
  4. 计算2000-2019各省份产业结构合理化指数
  5. 【Script系列】makefile的override指示符与gcc -ldl选项作用
  6. 书论02 赵壹《非草书》
  7. 天云数据历史数据查询解决方案,全量·全渠道·多维度·7*24h随时随地想查就查
  8. cmd从c盘切换到其他盘
  9. 晕-西数绿盘装雪豹难道有问题?
  10. 西门子S7200系列PLC数据采集和点表自动侦测获取