To run a single instance of a program, I use the following approach, which is recommended in this link rather than the approach presented here.
C#:
using System;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security.AccessControl;
using System.Security.Principal;
using System.Threading;
using System.Windows;
namespace My_App
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
static class GlobalMutex
{
public static void SingleGlobalInstance()
{
string AppGuid = ((GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value.ToString();
string MutexId = string.Format("Global\\{{{0}}}", AppGuid);
bool CreatedNew;
var AllowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow);
var SecuritySettings = new MutexSecurity();
SecuritySettings.AddAccessRule(AllowEveryoneRule);
using (var mutex = new Mutex(false, MutexId, out CreatedNew, SecuritySettings))
{
var HasHandle = false;
try
{
try
{
HasHandle = mutex.WaitOne(5000, false);
switch (HasHandle)
{
case false:
throw new TimeoutException("Timeout waiting for exclusive access");
}
}
catch (AbandonedMutexException)
{
HasHandle = true;
}
}
finally
{
switch (HasHandle)
{
case true:
mutex.ReleaseMutex();
break;
}
}
}
}
}
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
GlobalMutex.SingleGlobalInstance();
base.OnStartup(e);
}
}
}
But I get the following error:
Index was outside the bounds of the array
at line 5.
What is the cause of this error and how can it be resolved?
I use the following tools:
Thank you for your time.
Best regards