Guest User

Untitled

a guest
Dec 11th, 2017
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.59 KB | None | 0 0
  1. static void Main()
  2. {
  3. string mutex_id = "MY_APP";
  4. using (Mutex mutex = new Mutex(false, mutex_id))
  5. {
  6. if (!mutex.WaitOne(0, false))
  7. {
  8. MessageBox.Show("Instance Already Running!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Hand);
  9. return;
  10. }
  11. // Do stuff
  12. }
  13. }
  14.  
  15. private static bool AlreadyRunning()
  16. {
  17. Process[] processes = Process.GetProcesses();
  18. Process currentProc = Process.GetCurrentProcess();
  19.  
  20. foreach (Process process in processes)
  21. {
  22. try
  23. {
  24. if (process.Modules[0].FileName == System.Reflection.Assembly.GetExecutingAssembly().Location
  25. && currentProc.Id != process.Id)
  26. return true;
  27. }
  28. catch (Exception)
  29. {
  30.  
  31. }
  32. }
  33.  
  34. return false;
  35. }
  36.  
  37. private static bool AlreadyRunning()
  38. {
  39. Process[] processes = Process.GetProcesses();
  40. Process currentProc = Process.GetCurrentProcess();
  41. logger.LogDebug("Current proccess: {0}", currentProc.ProcessName);
  42. foreach (Process process in processes)
  43. {
  44. if (currentProc.ProcessName == process.ProcessName && currentProc.Id != process.Id)
  45. {
  46. logger.LogInformation("Another instance of this process is already running: {pid}", process.Id);
  47. return true;
  48. }
  49. }
  50. return false;
  51. }
  52.  
  53. bool createdNew;
  54. using (Mutex mutex = new Mutex(true, "MyApplicationName", out createdNew))
  55. {
  56. if (createdNew) {
  57. // process
  58. }
  59. else {
  60. // in my case, quietly exit
  61. }
  62. }
Add Comment
Please, Sign In to add comment