Outlook VSTO问题:修改附件DisplayName后当前窗口不显示新名称
解决Outlook VSTO修改附件DisplayName后UI不刷新的问题
问题原因
修改Attachment.DisplayName属性后,Outlook不会自动同步更新当前窗口的UI,必须手动触发刷新操作,才能让附件的新名称立即显示。
解决方案
根据当前邮件的显示场景(单独打开的Inspector窗口/主窗口预览窗格),执行对应的刷新逻辑:
1. 单独打开的邮件窗口(Inspector)
获取邮件对应的Inspector对象并调用Refresh()方法,直接刷新窗口:
public void RenameAttachment(Office.IRibbonControl control) { Outlook.Attachment attachment = null; Outlook.AttachmentSelection selection = null; Outlook.Inspector inspector = null; Outlook.MailItem mailItem = null; try { selection = control.Context as Outlook.AttachmentSelection; if (selection != null) { attachment = selection[1]; if (attachment != null) { attachment.DisplayName = "NewName12345"; // 获取附件所属的邮件项 mailItem = attachment.Parent as Outlook.MailItem; if (mailItem != null) { // 获取并刷新对应的Inspector窗口 inspector = mailItem.GetInspector; inspector.Refresh(); } } } } finally { // 释放所有COM对象,避免内存泄漏 if (mailItem != null) Marshal.ReleaseComObject(mailItem); if (inspector != null) Marshal.ReleaseComObject(inspector); if (attachment != null) Marshal.ReleaseComObject(attachment); if (selection != null) Marshal.ReleaseComObject(selection); Marshal.ReleaseComObject(control.Context); Marshal.ReleaseComObject(control); } }
2. 主窗口预览窗格中的邮件
若邮件在主窗口的预览窗格显示,需要通过重新选中邮件触发预览窗格刷新:
// 在上述代码的try块中,获取mailItem后添加以下逻辑 if (mailItem != null) { Outlook.Explorer activeExplorer = Globals.ThisAddIn.Application.ActiveExplorer; if (activeExplorer != null && activeExplorer.Selection.Count > 0) { // 先清空选择再重新选中当前邮件,触发预览窗格更新 object selectedItem = activeExplorer.Selection[1]; activeExplorer.ClearSelection(); activeExplorer.AddToSelection(selectedItem); Marshal.ReleaseComObject(selectedItem); Marshal.ReleaseComObject(activeExplorer); } }
注意事项
- 务必正确释放所有Outlook COM对象,防止内存泄漏。
- 需根据邮件的实际显示场景选择对应的刷新方式,才能确保UI立即更新。
内容的提问来源于stack exchange,提问作者DaGrooveNL
相关产品推荐
相关产品推荐

