用例:用户需要能够将电子邮件项目从 Outlook 拖放到我的 WinForms (.Net 4) 应用程序中的表单上。应用程序以 .msg 格式保存这些项目并将它们存储在预定位置。
问题:我的代码对来自其他来源的拖放并不可靠(例如,将 jpeg 从 IE 拖到表单上会触发相同的事件)。这是因为我无法确定拖动的项目是否是 Outlook 对象,或者拖动的项目来自哪个源。
是否有一种解决方法,使我只能接受特定类型的拖放项目?这是我在 DragDrop 事件处理程序中的代码:
Outlook.Application outlook = new Outlook.Application();
Outlook.Selection sel = outlook.ActiveExplorer().Selection;
try
{
foreach (object item in sel)
{
if (item is Outlook.MailItem)
{
var mail = item as Outlook.MailItem;
CopyMailItemToLocalTempDir(mail);
txtComment.Text = "Email from " + mail.SenderName + " Regarding " + mail.Subject;
}
}
}
finally
{
// This is hokey but it prevents Outlook from remembering previously selected items
// - refer http://stackoverflow.com/questions/14090420/interop-outlook-doesnt-clear-selected-mails-at-drag-and-drop
var folder = outlook.ActiveExplorer().CurrentFolder;
outlook.ActiveExplorer().CurrentFolder = outlook.GetNamespace("MAPI").GetDefaultFolder(Outlook.OlDefaultFolders.olFolderContacts);
Thread.Sleep(50);
outlook.ActiveExplorer().CurrentFolder = folder;
Marshal.ReleaseComObject(sel);
Marshal.ReleaseComObject(outlook);
sel = null;
outlook = null;
}
从 Outlook 拖动时有关 DragEventArgs 对象 (e) 的一些详细信息:
e.Data.GetFormats() returns:
{string[15]}
[0]: "RenPrivateSourceFolder"
[1]: "RenPrivateLatestMessages"
[2]: "RenPrivateMessages"
[3]: "RenPrivateItem"
[4]: "FileGroupDescriptor"
[5]: "FileGroupDescriptorW"
[6]: "FileDrop"
[7]: "FileNameW"
[8]: "FileName"
[9]: "FileContents"
[10]: "Object Descriptor"
[11]: "System.String"
[12]: "UnicodeText"
[13]: "Text"
[14]: "CSV"
e.Data.GetData("Text") returns:
"From\tSubject\tReceived\tSize\tCategories\t\r\nJoe Sender\tThis is the email subject\t10:51 AM\t3 KB\t\t"