如何在Outlook邮件正文右键菜单添加VSTO C#插件按钮并获取选中文本?
在VSTO C# Outlook插件中添加邮件正文右键菜单按钮并获取阅读模式选中文本
一、通过RibbonXML定义右键菜单
在VSTO插件项目中添加**Ribbon(XML)**项,替换默认的RibbonXML内容为以下代码,实现向邮件正文右键菜单插入自定义按钮:
<customUI xmlns="http://schemas.microsoft.com/office/2009/07/customui"> <contextMenus> <!-- 绑定Outlook内置的邮件正文右键菜单 --> <contextMenu idMso="ContextMenuMailText"> <button id="BtnGetSelectedText" label="获取选中文本" imageMso="FindDialog" onAction="OnGetSelectedTextClick" insertBeforeMso="Cut"/> </contextMenu> </contextMenus> </customUI>
说明:
idMso="ContextMenuMailText"是Outlook原生的邮件正文右键菜单标识,确保按钮出现在正确的上下文里imageMso可直接使用Office内置图标,这里用了查找对话框的图标,你可以替换成其他内置IDinsertBeforeMso="Cut"设置按钮插入到“剪切”选项之前
二、实现按钮点击逻辑与文本获取
在Ribbon对应的C#代码类中,编写按钮点击事件,通过Word编辑器对象获取阅读模式下的选中文本:
using Microsoft.Office.Core; using Microsoft.Office.Interop.Outlook; using Microsoft.Office.Interop.Word; using System.Windows.Forms; public class RibbonMain : Office.IRibbonExtensibility { private Office.IRibbonUI _ribbonUI; public RibbonMain() { } // 返回RibbonXML内容(对应项目中的资源文件) public string GetCustomUI(string ribbonID) { return Properties.Resources.RibbonMain; } public void Ribbon_Load(Office.IRibbonUI ribbonUI) { _ribbonUI = ribbonUI; } // 自定义按钮点击事件 public void OnGetSelectedTextClick(Office.IRibbonControl control) { // 获取当前Explorer窗口选中的邮件 Explorer activeExplorer = Globals.ThisAddIn.Application.ActiveExplorer(); Selection mailSelection = activeExplorer.Selection; if (mailSelection.Count == 0) return; if (mailSelection[1] is MailItem currentMail) { // 获取邮件对应的Word编辑器对象 Inspector mailInspector = currentMail.GetInspector; Document mailDoc = mailInspector.WordEditor as Document; if (mailDoc == null) { MessageBox.Show("无法访问邮件正文编辑器"); return; } // 读取选中文本 string selectedContent = mailDoc.Application.Selection.Text.Trim(); if (!string.IsNullOrEmpty(selectedContent)) { MessageBox.Show($"选中内容:\n{selectedContent}"); // 此处添加你的业务处理逻辑 } else { MessageBox.Show("未选中任何文本"); } } } }
三、关键注意事项
- 必须引用
Microsoft.Office.Interop.Word程序集:右键项目→添加→引用→COM→选择"Microsoft Word xx.x Object Library" - 阅读模式下,确保
ActiveExplorer.Selection能正确获取当前邮件;若使用单独的Inspector窗口阅读,可调整为Application.ActiveInspector()获取 - 处理异常:对于加密、受保护的邮件,
WordEditor可能无法访问,需添加try-catch块捕获异常
内容的提问来源于stack exchange,提问作者user22905514
相关产品推荐
相关产品推荐

