Reputation: 71
I have tried looking for the answer to this question... Forgive me if I have overlooked it.
What I am trying to do is automate sending an email. I have everything I want in this code but the code assumes that Outlook is NOT open.
Is there a way for me to test if Outlook is open before it opens another instance of Outlook?
Microsoft.Win32.RegistryKey key =
Microsoft.Win32.Registry.LocalMachine.OpenSubKey("Software\\microsoft\\windows\\currentversion\\app paths\\OUTLOOK.EXE");
string path = (string)key.GetValue("Path");
if (path != null)
System.Diagnostics.Process.Start("OUTLOOK.EXE");
else
MessageBox.Show("There is no Outlook in this computer!", "SystemError", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
Upvotes: 4
Views: 7026
Reputation: 409
Since I like clean one-liners, here's what I used:
if (System.Diagnostics.Process.GetProcessesByName("OUTLOOK").Any())
return true;
Upvotes: 16
Reputation: 1395
using System.Diagnostics; //to make the Process work
Process[ ] processlist = Process.GetProcessesByName
("OUTLOOK:);
If (processlist.Length>0)
{
//outlook is open
}
Upvotes: -1
Reputation: 851
You could use the Process class e.g.
Process[] localByName = Process.GetProcessesByName("outlook");
// empty array if no outlook process found.
if(localByName.Length > 0)
{ /*do work because outlook is already open*/}
else
{/* start outlook */}
another way could be a wql-query
WqlObjectQuery wqlQuery = new WqlObjectQuery("SELECT * FROM Win32_Process");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(wqlQuery);
foreach (ManagementObject process in searcher.Get())
{
var name = process.GetPropertyValue("Name"); // e.g. outlook.exe
}
Upvotes: 0
Reputation: 16377
Here is one way you can test if Outlook is open, and if it is, you "grab" the current instance. In your catch block, you can open your new instance the way you have listed:
Outlook.Application ol;
try
{
ol = (Outlook.Application)Marshal.GetActiveObject("Outlook.Application");
}
catch (Exception ex)
{
// open your new instance
}
Upvotes: 5
Reputation: 450
int procCount = 0;
Process[] processlist = Process.GetProcessesByName("OUTLOOK");
foreach (Process theprocess in processlist)
{
procCount++;
}
if (procCount > 0)
{
//outlook is open
}
Upvotes: 6