Outlook Showing in Process even after closing - C#

Rohit Pawar 0 Reputation points
2023-10-20T08:33:43.2966667+00:00

I am writing a code to such that I will get a trigger when ever outlook opens

Process[] processlist = System.Diagnostics.Process.GetProcessesByName("OUTLOOK");
if (processlist.Count() > 0)
{
   MessageBox.Show("Outlook Opened");
}

Works great for the first time when I open outlook, but the message box continue to show even after outlook is closed .

I also checked the background process there is no outlook process running. Help appreciated :) .

Developer technologies | Windows Presentation Foundation
Outlook | Windows | Classic Outlook for Windows | For business
Developer technologies | ASP.NET | Other
Developer technologies | C#
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Viorel 122.6K Reputation points
    2023-10-20T08:41:05.5766667+00:00

    Try this:

    if( processlist.Any( p => !p.HasExited ) )
    {
        MessageBox.Show("Outlook Opened");
    }
    
    0 comments No comments

  2. Hui Liu-MSFT 48,681 Reputation points Microsoft External Staff
    2023-10-23T02:31:37.13+00:00

    Hi,@Rohit Pawar.Welcome to Microsoft Q&A Forum, To address this issue, you might consider using the Exited event of the Process class to handle the event when Outlook is closed. Here is an example of how to modify your code to include event handling for the Exited event:

       Process[] processlist = Process.GetProcessesByName(processName);
    
                if (processlist.Length > 0)
                {
                    MessageBox.Show("Outlook Opened");
    
                    foreach (Process process in processlist)
                    {
                        process.EnableRaisingEvents = true;
                        process.Exited += OutlookExited;
                    }
                }
      private static void OutlookExited(object sender, EventArgs e)
            {
                MessageBox.Show("Outlook Closed");
            }
    
    
    

    If you still have questions, please feel free to let me know. The problem will be better solved if more details are described (steps, error messages, and code to reproduce the problem).


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.