WPF:拖放电子邮件窗体Outlook后出现崩溃(Office Interop)

时间:2017-11-02 12:56:33

标签: c# wpf outlook office-interop

在我的WPF应用程序中,我使用Microsoft.Office.Interop.Outlook在我的应用程序中拖放电子邮件并处理它们。

但偶尔会在发送电子邮件后崩溃Outlook崩溃。没有例外,我可以找到de Windows事件日志中的App Crash语句......

任何想法可能是什么原因?

    private void HandleDrop()
    {
        int mailItemsHandled = HandleMailItemDrop();
        SynchronizationContext synchronizationContext = SynchronizationContext.Current;
        synchronizationContext.Post(new SendOrPostCallback(arg =>
        {
            if (mailItemsHandled > 1)
            {
                // do something
            }
            else if (mailItemsHandled == 1)
            {
                // do something
            }
        }), "null");
    }

 private int HandleMailItemDrop()
    {
        Microsoft.Office.Interop.Outlook.Application Outlook = Marshal.GetActiveObject("Outlook.Application") as Microsoft.Office.Interop.Outlook.Application;
        //new Microsoft.Office.Interop.Outlook.Application();
        int mailItemsHandled = 0;
        Microsoft.Office.Interop.Outlook.Explorer oExplorer = Outlook?.ActiveExplorer();
        if (oExplorer != null)
        {
            Microsoft.Office.Interop.Outlook.Selection oSelection = oExplorer.Selection;
            if (oSelection != null)
            {
                List<Email> items = new List<Email>();
                foreach (object item in oSelection)
                {
                    Microsoft.Office.Interop.Outlook.MailItem mailItem = item as Microsoft.Office.Interop.Outlook.MailItem;
                    if (mailItem != null)
                    {
                        Email email = // do some logic with the mailItem
                        items.Add(email);
                        mailItemsHandled++;
                        Marshal.ReleaseComObject(mailItem);
                    }
                }
                Marshal.ReleaseComObject(oSelection);
            }
            Marshal.ReleaseComObject(oExplorer);
        }
        Marshal.ReleaseComObject(Outlook);
        Marshal.FinalReleaseComObject(Outlook);
        return mailItemsHandled;
    }

0 个答案:

没有答案