Prevent Multiple Instances of a Given App in .Net

Prevent multiple instances of a given app in .NET?

Use Mutex. One of the examples above using GetProcessByName has many caveats. Here is a good article on the subject:

http://odetocode.com/Blogs/scott/archive/2004/08/20/401.aspx

[STAThread]
static void Main()
{
using(Mutex mutex = new Mutex(false, "Global\\" + appGuid))
{
if(!mutex.WaitOne(0, false))
{
MessageBox.Show("Instance already running");
return;
}

Application.Run(new Form1());
}
}

private static string appGuid = "c0a76b5a-12ab-45c5-b9d9-d693faa6e7b9";

How can I prevent launching my app multiple times?

At program startup check if same process is already running:

using System.Diagnostics;

static void Main(string[] args)
{
String thisprocessname = Process.GetCurrentProcess().ProcessName;

if (Process.GetProcesses().Count(p => p.ProcessName == thisprocessname) > 1)
return;
}

What is the safest way to prevent multiple instances of a program?

The safest way is to use the built-in support in .NET, WindowsFormsApplicationBase.IsSingleInstance property. Hard to guess if it is appropriate, you didn't make much effort describing your exact needs. And no, nothing changed in the past 5 years. – Hans Passant Jan 7 at 0:38

This was the best answer but Hans didn't submit it as an answer.

How to prevent multiple app loading, but allow loading its different instances?

You could use Mutex to prevent multiple instances from your app to run simultaneously regardless of the name or path of the executable:

Prevent multiple instances of a given app in .NET?

Prevent running multiple instances of a mono app

I came up with this answer. Call this method passing it a unique ID

    public static void PreventMultipleInstance(string applicationId)
{
// Under Windows this is:
// C:\Users\SomeUser\AppData\Local\Temp\
// Linux this is:
// /tmp/
var temporaryDirectory = Path.GetTempPath();

// Application ID (Make sure this guid is different accross your different applications!
var applicationGuid = applicationId + ".process-lock";

// file that will serve as our lock
var fileFulePath = Path.Combine(temporaryDirectory, applicationGuid);

try
{
// Prevents other processes from reading from or writing to this file
var _InstanceLock = new FileStream(fileFulePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
_InstanceLock.Lock(0, 0);
MonoApp.Logger.LogToDisk(LogType.Notification, "04ZH-EQP0", "Aquired Lock", fileFulePath);

// todo investigate why we need a reference to file stream. Without this GC releases the lock!
System.Timers.Timer t = new System.Timers.Timer()
{
Interval = 500000,
Enabled = true,
};
t.Elapsed += (a, b) =>
{
try
{
_InstanceLock.Lock(0, 0);
}
catch
{
MonoApp.Logger.Log(LogType.Error, "AOI7-QMCT", "Unable to lock file");
}
};
t.Start();

}
catch
{
// Terminate application because another instance with this ID is running
Environment.Exit(102534);
}
}

Is it possible to completely prevent multiple instance on .NET Compact Framework?

Your code is almost fine. only missing thing is to remove the application exit and put in there the code needed to bring current running instance on top. i did this in the past so you do not need to disable or hide the icon you simply detect the already running instance and bring it on foreground.

Edit:

here some code snippet:

[DllImport("coredll.dll")]
private static extern IntPtr FindWindow(IntPtr className, string windowName);

[DllImport("coredll.dll")]
internal static extern int SetForegroundWindow(IntPtr hWnd);

[DllImport("coredll.dll")]
private static extern bool SetWindowPos(IntPtr hwnd, int hwnd2, int x,int y, int cx, int cy, int uFlags);

if (IsInstanceRunning())
{
IntPtr h = FindWindow(IntPtr.Zero, "Form1");
SetForegroundWindow(h);
SetWindowPos(h, 0, 0, 0, Screen.PrimaryScreen.Bounds.Width,Screen.PrimaryScreen.Bounds.Height, 0x0040);

return;
}

check these links for more info...

http://www.nesser.org/blog/archives/56 (including comments)

What is the best way to make a single instance application in Compact Framework?



Related Topics



Leave a reply



Submit