Outlook VSTO - Calling TypeText on Selection throws “This command is not available” Exception

淺唱寂寞╮ 提交于 2019-12-25 08:09:09

问题


Calling TypeText on Selection throws "This command is not available." exception

Below is my code

public void AddFilePaths(List<string> urls)
{
    if (urls.Count > 0)
    {
        MailItem mi = null;
        bool newMailItem = false;

        mi = MyAddIn.Application.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem);
        mi.Body = "New email body"; 
        newMailItem = true;

        mi.Display();
        inspector = MyAddIn.Application.ActiveInspector();

        if (mi != null)
        {
            foreach (var url in urls)
            {
                AddPathToActiveInspector(urls);
            }
        }
    }
}

public void AddLinkToCurrentInspector(string url)
{
    var inspector = MyAddIn.Application.ActiveInspector();
    var currMessage = inspector.CurrentItem;
    Microsoft.Office.Interop.Word.Document word = currMessage.GetInspector.WordEditor; 
    dynamic wordapp = word.Application;
    const string text = "\n"; // thisfor some reason will not add new line
    Microsoft.Office.Interop.Word.Selection sel = word.Windows[1].Selection;
    sel.TypeText(text); // this often errors
    string address = url;
    string subAddress = "";
    string screenTip = "";
    string textToDisplay = url; 
    wordapp.ActiveDocument.Hyperlinks.Add(sel.Range, ref address, ref subAddress, ref screenTip, ref textToDisplay);
    if (word.ProtectionType != Microsoft.Office.Interop.Word.WdProtectionType.wdNoProtection) word.Unprotect(); 
    sel.TypeText(" "); 
}

回答1:


You don't need to call TypeText - just set the Text property:

Application.ActiveInspector.WordEditor.Application.Selection.Text = "test"



回答2:


Based on answer in this question, I also resolved this issue. The code that works better than code above and is more easy to follow is below. Many thanks to @joeshwa:

    public void AddLinkToCurrentInspector(string url)
    {
        object link = url;
        object result = "url";
        object missing = Type.Missing;

        var inspector = MyAddIn.Application.ActiveInspector();
        MailItem currMessage = inspector.CurrentItem;
        Microsoft.Office.Interop.Word.Document doc = currMessage.GetInspector.WordEditor;
        Microsoft.Office.Interop.Word.Selection sel = doc.Windows[1].Selection;
        doc.Hyperlinks.Add(sel.Range, ref result, ref missing, ref missing, ref link, ref missing);
        sel.EndKey(Microsoft.Office.Interop.Word.WdUnits.wdLine);
        sel.InsertAfter("\n");
        sel.MoveDown(Microsoft.Office.Interop.Word.WdUnits.wdLine);
    }


来源:https://stackoverflow.com/questions/38982358/outlook-vsto-calling-typetext-on-selection-throws-this-command-is-not-availab

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!