Viktoriusrex
Viktoriusrex

Reputation: 23

Outlook: Closing MailItem dialog closes Outlook application too

I have a problem with following code:

Condition 1 is, Outlook is not running for the start of Main!!! Condition 2 Outlook is not shown from tray!!!

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();
    }
}

and

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;
    }
}

Upvotes: 0

Views: 436

Answers (1)

Dmitry Streblechenko
Dmitry Streblechenko

Reputation: 66245

Outlook closes when its last window is closed even if there are outstanding references to any of its objects. That was done on purpose in the Outlook 2007 timeframe to prevent misbehaving external app from keeping Outlook open when the user wants to close it.

IF I remember correctly, you can prevent Outlook from closing by holding a reference to an Inspector or Explorer object (e.g. MailItem.GetInspector or MAPIFolder.GetExplorer()).

Upvotes: 2

Related Questions