Outlook:关闭MailItem对话框也会关闭Outlook应用程序

时间:2015-02-26 15:31:50

标签: c# outlook

我遇到以下代码问题:

条件1是,Outlook没有为Main的开始运行!!! 条件2 Outlook不显示托盘!!!

class Program
{
    private static Application _appl;

    private static void Main(string[] args)
    {
        Sample sample = new Sample();
        Console.WriteLine(sample.IsOutlookRunning());

        _appl = sample.GetApplicationObject();

        Thread.Sleep(new TimeSpan(0, 0, 0, 5));
        if (sample.IsOutlookRunning())
        {
            Console.WriteLine(sample.IsOutlookRunning());
        }

        Console.ReadKey();
        MailItem mailItem = _appl.CreateItem(OlItemType.olMailItem);
        mailItem.Display();

        Thread.Sleep(new TimeSpan(0, 0, 0, 5));

        //_appl ist not running more!!!!!!!!!!!!!!!!!!!!!

        Console.ReadKey();
        MailItem mailItem2 = _appl.CreateItem(OlItemType.olMailItem);
        mailItem2.Display();

        Console.ReadKey();
    }
}

public class Sample
{
    private Outlook.Application _application;

    public Outlook.Application GetApplicationObject()
    {

        // Check whether there is an Outlook process running.
        if (Process.GetProcessesByName("OUTLOOK").Count() > 0)
        {

            // If so, use the GetActiveObject method to obtain the process and cast it to an Application object.
            _application = Marshal.GetActiveObject("Outlook.Application") as Outlook.Application;
        }
        else
        {
            // If not, create a new instance of Outlook and log on to the default profile.
            _application = new Outlook.Application();
            Outlook.NameSpace nameSpace = _application.GetNamespace("MAPI");
            nameSpace.Logon(Missing.Value, Missing.Value, false, Missing.Value);
            nameSpace = null;
        }

        // Return the Outlook Application object.
        return _application;
    }
}

1 个答案:

答案 0 :(得分:1)

即使对其任何对象有未完成的引用,Outlook也会在其最后一个窗口关闭时关闭。这是在Outlook 2007时间范围内有意进行的,以防止行为不当的外部应用程序在用户想要关闭时保持Outlook打开。

如果我没记错的话,你可以通过保持对Inspector或Explorer对象的引用来阻止Outlook关闭(例如MailItem.GetInspector或MAPIFolder.GetExplorer())。