Try adding this line:
[assembly: Guid( "F6341D4D-5A4D-429F-B587-28CD958B27F2" )]
to any source file, outside of classes and namespaces (or to AssemblyInfo.cs file if your project contains it).
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
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:
NET Framework 4.5
WPF
Thank you for your time.
Best regards
Try adding this line:
[assembly: Guid( "F6341D4D-5A4D-429F-B587-28CD958B27F2" )]
to any source file, outside of classes and namespaces (or to AssemblyInfo.cs file if your project contains it).
Hi @Reza Jaferi ,
string AppGuid = ((GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value.ToString();
This code is for get application GUID as defined in AssemblyInfo.cs
.
It could not be obtained in debug mode.
Please try to debug in release mode.
Best Regards,
Jiale
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.