Reputation: 217
I am trying to input some predefined text into a New email in Outlook 365 using VSTO C#. I have written this basic code:
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
inspectors = this.Application.Inspectors;
inspectors.NewInspector +=
new Outlook.InspectorsEvents_NewInspectorEventHandler(Inspectors_NewInspector);
}
void Inspectors_NewInspector(Microsoft.Office.Interop.Outlook.Inspector Inspector)
{
try
{
if (this.Application.ActiveExplorer().Selection.Count > 0)
{
if (Inspector.CurrentItem is Outlook.MailItem)
{
Word.Document wordDocument = Inspector.WordEditor as Word.Document;
Word.Range wordRange = wordDocument.Range(0, 0);
wordRange.Text = "Text";
}
}
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message);
}
}
While debugging, at line: Word.Document wordDocument = Inspector.WordEditor as Word.Document; I am getting error "The Operation failed".
I checked Inspector.WordEditor using Outlook spy also and it has data too.
The same expression is working correct when I craete mailitem by myself using:
Outlook.MailItem mailItem = (new Outlook.Application()).CreateItem(Outlook.OlItemType.olMailItem);
I searched on internet a lot, but nothing found something workable in for my case.
I want to know why this is happening and how I can solve this. Can anybody please help me?
Upvotes: 1
Views: 1108
Reputation: 66255
The inspector might not be initialized yet by the time NewInspector
handler is called. Try to wait until Inspector.Activate
event fires for the very first time (it can fire multiple times).
Upvotes: 1