App.xaml.cs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Configuration;
  4. using System.Data;
  5. using System.Linq;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. using System.Windows;
  9. using System.Windows.Input;
  10. namespace PRSRecordingNotes
  11. {
  12. /// <summary>
  13. /// Interaction logic for App.xaml
  14. /// </summary>
  15. public partial class App : Application
  16. {
  17. #region Constants and Fields
  18. /// <summary>The event mutex name.</summary>
  19. private const string UniqueEventName = "27722504-3ECA-4493-A942-DF08FFD92500";
  20. /// <summary>The unique mutex name.</summary>
  21. private const string UniqueMutexName = "65B5069F-33AB-42A1-AB42-3E495097A859";
  22. /// <summary>The event wait handle.</summary>
  23. private EventWaitHandle eventWaitHandle;
  24. /// <summary>The mutex.</summary>
  25. private Mutex mutex;
  26. #endregion
  27. #region Methods
  28. /// <summary>The app on startup.</summary>
  29. /// <param name="sender">The sender.</param>
  30. /// <param name="e">The e.</param>
  31. private void AppOnStartup(object sender, StartupEventArgs e)
  32. {
  33. bool isOwned;
  34. this.mutex = new Mutex(true, UniqueMutexName, out isOwned);
  35. this.eventWaitHandle = new EventWaitHandle(false, EventResetMode.AutoReset, UniqueEventName);
  36. // So, R# would not give a warning that this variable is not used.
  37. GC.KeepAlive(this.mutex);
  38. if (isOwned)
  39. {
  40. // Spawn a thread which will be waiting for our event
  41. var thread = new Thread(
  42. () =>
  43. {
  44. while (this.eventWaitHandle.WaitOne())
  45. {
  46. Current.Dispatcher.BeginInvoke(
  47. (Action)(() => ((ScreenRecorderWindow)Current.MainWindow).BringToForeground()));
  48. }
  49. });
  50. // It is important mark it as background otherwise it will prevent app from exiting.
  51. thread.IsBackground = true;
  52. thread.Start();
  53. return;
  54. }
  55. // Notify other instance so it could bring itself to foreground.
  56. this.eventWaitHandle.Set();
  57. // Terminate this instance.
  58. this.Shutdown();
  59. }
  60. #endregion
  61. }
  62. }