My C# application needs to work close to Outlook. I've implemented a method that allows to load Outlook if it is not on yet. After this loading method I need to start working with emails, read Inbox folder etc. . . obviously, all these behaviours must be executed when Outlook is on, in particular if the main Outlook windows is ready.
Looking at the OOM I've found the application Startup
event, and I think I could use it to be sure the application is ready...but I don't know how to use it.
To share the idea of what I'm trying to do, here there is the code (simplified):
Main:
OutlookProvider p= new OutlookProvider();
p.Connect();
if(p.AppIsOn) {
// TO DO: start working
}
else
throw new Exception("Error; Unable to connect to Outlook.");
OutlookProvider class:
#region Fields
Outlook.Application oApp;
Outlook.MailItem oMail;
bool AppIsOn;
#endregion
OutlookProvider() { AppIsOn= false; }
Connect() {
try {
// try to connect to the possible running Outlook instance
oApp = (Outlook.Application)Marshal.GetActiveObject("Outlook.Application");
AppIsOn= true;
}
catch(Exception exc) {
// Outlook is not running, so I create my own Outlook instance
// here my app is null so an Exception will be thrown
oApp.Startup += new Outlook.ApplicationEvents_11_StartupEventHandler(SetAppIsOn);
oApp= (Outlook.Application)new Outlook.Application();
}
}
void SetAppIsOn() { AppIsOn= true;}
Can I use that event to solve my problem? And if yes how can I implement the Connect() method in order to set my boolean AppIsOn
variable?
To make sure Outlook is fully initialized, call Namespace.Logon. If Outlook is already running, the call will do nothing.
There is also no reason to call GetActiveObject - Outlook is a singleton, so creating a new object will return the existing object if Outlook is already running.