Outlook VSTO-在选择上调用TypeText会引发“此命令不可用";例外 [英] Outlook VSTO - Calling TypeText on Selection throws "This command is not available" Exception

查看:67
本文介绍了Outlook VSTO-在选择上调用TypeText会引发“此命令不可用";例外的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Selection上调用TypeText会引发此命令不可用".例外

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

下面是我的代码

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(" "); 
}

推荐答案

基于此问题的答案,我也解决了此问题.下面的代码比上面的代码工作得更好,并且更易于遵循.非常感谢@joeshwa:

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);
    }

这篇关于Outlook VSTO-在选择上调用TypeText会引发“此命令不可用";例外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆