用例:用戶需要將我的WinForms(.Net 4)應用程序中從Outlook拖放電子郵件項目到表單中的能力。應用程序以.msg格式保存這些項目並將它們存儲在預定位置。C#WinForms:識別拖放操作事件的類型
問題:我的代碼對於從其他來源的拖放(例如,將IE中的jpeg拖到表單上觸發相同的事件)不夠穩健。這是因爲我無法確定拖動的項目是否是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"
還沒有找到一個明確的回答我的問題,但這篇文章是最接近:http://www.codeproject.com/Articles/28209/Outlook-Drag-and- Drop-in-C –