How to

prevent opening multiple instance of application

Published: 11. January 2014 | Updated: 11. January 2014
License: Microsoft Public License (MS-PL)
Categories: Winforms, WPF
Tags: C# Security Threading Windows Winforms WPF
Was this snippet helpful for you? YESYES / NONO
Get Analyzant!

Check your entire website from code to content in minutes with Analyzant, the free analysis suite.

Free download at analyzant.com

Import namespaces (WPF)

using System;
using System.Threading;
using System.Windows;

Code (WPF)

public class App : Application
{
    private static readonly Mutex Mutex = new Mutex(false, "e1a1edfa-7382-41e5-ab56-9b0841ed2071"); // application identifier

    [STAThread]
    private static void Main()
    {
        if (!Mutex.WaitOne(TimeSpan.FromSeconds(0), false))
        {
            // another instance is already running
            return;
        }

        var app = new App();
        var window = new MainWindow();
        app.Run(window);
    }
}

Import namespaces (Winforms)

using System;
using System.Windows.Forms;

Code (Winforms)

static class Program
{
    private static readonly Mutex Mutex = new Mutex(false, "e1a1edfa-7382-41e5-ab56-9b0841ed2071"); // application identifier

    [STAThread]
    static void Main()
    {
        if (!Mutex.WaitOne(TimeSpan.FromSeconds(0), false))
        {
            // another instance is already running
            return;
        }

        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }
}
Send us feedback about this snippet »



Related Snippets: