From 635d4492aa590b93939e0311c083ad184cfa4a6d Mon Sep 17 00:00:00 2001 From: bluepilledgreat <97983689+bluepilledgreat@users.noreply.github.com> Date: Sat, 3 Feb 2024 13:24:28 +0000 Subject: [PATCH] use mutexes --- Bloxstrap/App.xaml.cs | 15 +++++++++------ Bloxstrap/InterProcessLock.cs | 30 ++++++++++++++++++++++++++++++ Bloxstrap/NativeMethods.txt | 3 +-- 3 files changed, 40 insertions(+), 8 deletions(-) create mode 100644 Bloxstrap/InterProcessLock.cs diff --git a/Bloxstrap/App.xaml.cs b/Bloxstrap/App.xaml.cs index f6e7072..ad3b761 100644 --- a/Bloxstrap/App.xaml.cs +++ b/Bloxstrap/App.xaml.cs @@ -163,19 +163,22 @@ namespace Bloxstrap InstallChecker.CheckUpgrade(); #endif + using InterProcessLock processLock = new InterProcessLock("Process", TimeSpan.FromMilliseconds(100)); + if (LaunchSettings.IsMenuLaunch) { - Process? menuProcess = Process.GetProcesses().Where(x => x.MainWindowTitle == $"{ProjectName} Menu").FirstOrDefault(); + using InterProcessLock menuLock = new InterProcessLock("Menu", TimeSpan.FromMilliseconds(100)); - if (menuProcess is not null) + if (!menuLock.IsAcquired) { - var handle = menuProcess.MainWindowHandle; - Logger.WriteLine(LOG_IDENT, $"Found an already existing menu window with handle {handle}"); - PInvoke.SetForegroundWindow((HWND)handle); + Frontend.ShowMessageBox( + "The Bloxstrap menu is already open.", + MessageBoxImage.Error + ); } else { - if (Process.GetProcessesByName(ProjectName).Length > 1 && !LaunchSettings.IsQuiet) + if (!processLock.IsAcquired && !LaunchSettings.IsQuiet) Frontend.ShowMessageBox( Bloxstrap.Resources.Strings.Menu_AlreadyRunning, MessageBoxImage.Information diff --git a/Bloxstrap/InterProcessLock.cs b/Bloxstrap/InterProcessLock.cs new file mode 100644 index 0000000..e1938e8 --- /dev/null +++ b/Bloxstrap/InterProcessLock.cs @@ -0,0 +1,30 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Bloxstrap +{ + public class InterProcessLock : IDisposable + { + public Mutex Mutex { get; private set; } + + public bool IsAcquired { get; private set; } + + public InterProcessLock(string name, TimeSpan timeout) + { + Mutex = new Mutex(false, "Bloxstrap-" + name); + IsAcquired = Mutex.WaitOne(timeout); + } + + public void Dispose() + { + if (IsAcquired) + { + Mutex.ReleaseMutex(); + IsAcquired = false; + } + } + } +} diff --git a/Bloxstrap/NativeMethods.txt b/Bloxstrap/NativeMethods.txt index aaa0b6a..bc49657 100644 --- a/Bloxstrap/NativeMethods.txt +++ b/Bloxstrap/NativeMethods.txt @@ -1,5 +1,4 @@ -SetForegroundWindow -FlashWindow +FlashWindow GetWindowLong SetWindowLong EnumDisplaySettings