C# VSTO Outlook 传出消息超链接

C# VSTO Outlook Outgoing Message Hyperlink

我正在为 Outlook 2010 创建 C# VSTO 加载项。我正在尝试在正在处理的活动传出消息的插入点生成超链接(通过消息上的按钮插入超链接window 丝带)。加载项的所有其他功能(功能区按钮、访问 ActiveInspector().CurrentItem 等)工作正常。我正在使用这段代码:

object linktext = txtDisplayText.Text;
object result = "MY URL";
object missObj = Type.Missing;

Outlook.MailItem currentMessage = 
     Globals.ThisAddIn.Application.ActiveInspector().CurrentItem;
Word.Document doc = currentMessage.GetInspector.WordEditor;
object oRange = doc.Windows[1].Selection;
doc.Application.Selection.Hyperlinks.Add
    (oRange, ref result, ref missObj, ref missObj, ref linktext, ref missObj);

当我 运行 此代码时,我收到消息 "Command failed." 我怀疑我遗漏了一些关于 Outlook 如何使用 Microsoft Word 编辑器处理 Outlook 消息或我指定的方式oRange 中的选择对象。非常感谢任何帮助。

改为使用 MailItem class 的 HTMLBody 属性 在 ItemSend 事件处理程序中修改邮件正文(插入超链接)。您需要找到粘贴超链接的位置 <a href=.../>,修改 HTML 格式正确的字符串并将其分配回去。

这个问题确实是由为 Hyperlinks.Add 命令定义选择的方式引起的。选择需要键入 Microsoft Word 选择而不是对象类型(因为 Outlook 使用 Word 作为其编辑器):

Word.Selection objSel = doc.Windows[1].Selection;

因此,要在撰写过程中在 Outlook 邮件的插入点插入超链接,代码对 Word 和 Outlook 都有 using 语句:

using Outlook = Microsoft.Office.Interop.Outlook;
using Word = Microsoft.Office.Interop.Word;

然后是这段代码:

object linktext = txtDisplayText.Text;
object result = "MY URL";
object missObj = Type.Missing;

Outlook.MailItem currentMessage = 
     Globals.ThisAddIn.Application.ActiveInspector().CurrentItem;
Word.Document doc = currentMessage.GetInspector.WordEditor;
Word.Selection objSel = doc.Windows[1].Selection;
doc.Hyperlinks.Add
     (objSel.Range, ref result, ref missObj, ref missObj, ref linktext, ref missObj);

另外两项调整值得注意。因为 Word.Selection 类型用于超链接的锚点,所以 Hyperlinks.Add 命令需要从 doc.Application.Selection.Hyperlinks.Add 更改为 doc.Hyperlinks.Add。因为 Outlook 使用 Microsoft 的 Word 编辑器,所以 doc.Hyperlinks.Add 的锚点使用了一个范围:objSel.Range.