Search code examples
c#vstooutlook-addin

Outlook VSTO TypeText("text") Throws "The TypeText method or property is not available because the document is locked for editing" Exception


Calling TypeText("dummytext") on ActiveInspector WordEditor throws:

The TypeText method or property is not available because the document is locked for editing.

Here is my code:

var inspector = myMailItem.GetInspector;
dynamic w = inspector.WordEditor;
dynamic wa = w.Application;
wa.Selection.TypeText("sometext");

enter image description here


Solution

  • I have seen lots of issues if using selection this way. This is how I would do it

    object link = url;
    object res = "url";
    object missing = Type.Missing;
    
    // get active inspector (note that this assumes you work always on the active email message).
    var inspector = ThisAddIn.Application.ActiveInspector();
    MailItem email = inspector.CurrentItem;  // get the email message 
    Microsoft.Office.Interop.Word.Document document = email.GetInspector.WordEditor;
    Microsoft.Office.Interop.Word.Selection sel = document.Windows[1].Selection;
    doc.Hyperlinks.Add(sel.Range, ref res, ref missing, ref missing, ref link, ref missing);
    sel.EndKey(Microsoft.Office.Interop.Word.WdUnits.wdLine);  // move to the end of selection
    sel.InsertAfter("\n");  // insert new line
    sel.MoveDown(Microsoft.Office.Interop.Word.WdUnits.wdLine);  // move one line down