0

I have made a system tray app in C#, which is just running in the background. It is listening on a mailserver using Exchange WebServices, and performs a set of actions each time a mailaccount receives a message. It is using a number of Excel applications, which does not work properly if I convert to program to a service (which is why it has to be a system try app).

It is important that the program does not run more that once at a time. I have added a mutex lock, so I cannot run the program more than once on the same session. The problem is however, when I log into another session on the Windows Server (it can have two sessions per user), the program is not visible in the system tray, and I can open it again, so it runs twice, once in each session. How do I prevent this?

Thanks

Spliid
  • 478
  • 1
  • 4
  • 12
  • Create a file with a reserved name in e.g. `C:\temp` and keep it locked, so instance #2 will notice and exit? – Peter B Nov 25 '16 at 13:56
  • Which is the name of the mutex? If the mutex name starts with Global\ it is global to all terminal services sessions. You should also check the mutex permissions so it's accessible by all users. – Jesús López Nov 25 '16 at 14:03
  • see this SO question http://stackoverflow.com/questions/229565/what-is-a-good-pattern-for-using-a-global-mutex-in-c – Jesús López Nov 25 '16 at 14:05
  • Why cannot you support a single tray app per user session? Different user sessions should have their own tray apps. – Lex Li Nov 25 '16 at 14:48

1 Answers1

0

You should see all processes like this:

using System.Diagnostics;
var allProcceses = Process.GetProcesses();

Then you can check if your program is running.

MrApnea
  • 1,776
  • 1
  • 9
  • 17
  • But when I run the program, there will always be a process with that name. If my program is called mailChecker, and in that program I check if mailChecker is open, it will always return true, because mailChecker chekcs if mailChecker is open. Or am I wrong? – Spliid Nov 25 '16 at 14:08
  • You can use GetProcessesByName and look for mailChecker. If there was on already running you will see two entries, at that point you program can stop itself. – Mant101 Nov 25 '16 at 14:20
  • Sorry for the late reply. Either do as @Mant101 said and check for the number of processes. Or get the current process using 'Process.GetCurrentProcess()' and compare the Id, if they are the same you are looking at the current programs process. – MrApnea Nov 28 '16 at 10:56