Reputation: 3175
I am creating a C# VSTO add-in for Outlook 2010. I am attempting to generate a hyperlink at the insertion point of the active outgoing message that is being worked on (the hyperlink is inserted via a button on the message window ribbon). All other functions of the add-in (ribbon button, accessing the ActiveInspector().CurrentItem
, etc.) work fine. I am working with this code:
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);
When I run this code I get the message "Command failed." I suspect I am missing something either in regards to how Outlook uses Microsoft Word's editor for Outlook messages or in the way I have specified the selection object in oRange
. Any help is very much appreciated.
Upvotes: 1
Views: 1420
Reputation: 3175
This issue was indeed caused by the way the selection was defined for the Hyperlinks.Add
command. Instead of an object type, the selection needed to be typed as a Microsoft Word Selection (due to the fact that Outlook uses Word as its editor):
Word.Selection objSel = doc.Windows[1].Selection;
So to insert a hyperlink at the insertion point of an Outlook message during composition, the code has using statements for both Word and Outlook:
using Outlook = Microsoft.Office.Interop.Outlook;
using Word = Microsoft.Office.Interop.Word;
And then this code:
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);
Two other adjustments are worth noting. Because a Word.Selection
type was used for the anchor of the hyperlink, the Hyperlinks.Add
command needed to be changed from doc.Application.Selection.Hyperlinks.Add
to doc.Hyperlinks.Add
. And because Outlook uses Microsoft's Word editor, the anchor for doc.Hyperlinks.Add
used a range: objSel.Range
.
Upvotes: 2
Reputation: 49455
Use the HTMLBody property of the MailItem class for modifying the message body (inserting a hyperlink) in the ItemSend event handler instead. You need to find the place where to paste a hyperlink <a href=.../>
, modify the HTML well formed string and assign it back.
Upvotes: 0