C#: Ensure User only Runs One Copy of a Program
Using a mutex, you can ensure that multiple users can run a program, but each one can run only one copy of the program.
This can come in handy when users are logging into a Citrix server or other shared server, and you don't want to limit the application to running only once.
The following code illustrates this concept:
01.using System;
02.using System.Security.Principal;
03.using System.Threading;
04.using System.Windows.Forms;
05.
06.namespace WindowsFormsApplication2
07.{
08. static class Program
09. {
10. [STAThread]
11. static void Main()
12. {
13. bool ok;
14. string strMyAppName = "ObscureAppName";
15. string strMutex = WindowsIdentity.GetCurrent().Name.ToString();
16. strMutex = strMutex.Split('\\')[1];
17. strMutex += strMyAppName;
18. Mutex m = new Mutex(true, strMutex, out ok);
19. if (!ok)
20. {
21. MessageBox.Show("Already running");
22. Application.Exit();
23. }
24. if (ok)
25. {
26. Application.Run(new Form1());
27. GC.KeepAlive(m); // important!
28. }
29. }
30. }
31.}
This is an extension of the work previously done by Michael A. Covington here: http://www.ai.uga.edu/mc/SingleInstance.html