Prevent Multiple Instances for Windows Application in .NET

This code is used to prevent Multiple instances of same application.I googled a day for this.

//Add these References
using System.Threading;
using System.Reflection;
using System.Runtime.InteropServices;

Simple way to Prevent Multiple Instance.Write this code in Program.cs,

[STAThread]
static void Main()
{
    bool NewWindow;
    Mutex Mut = new Mutex(true, "YourApplicationName", out NewWindow);
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    if (!NewWindow)
        return;

    Application.Run(new Form1());
    GC.KeepAlive(Mut);
}

This is the another way,

[STAThread]
static void Main()
{
    bool NewWindow;
    Mutex Mut = new Mutex(true, "YourApplicationName", out NewWindow);
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    if (!NewWindow)
    {
       IntPtr hWnd = FindWindow("WindowsForms10.Window.8.app3", "YourApplicationName");
       if (hWnd != IntPtr.Zero)
       {
           WINDOWPLACEMENT placement = new WINDOWPLACEMENT();
           placement.length = Marshal.SizeOf(placement);

           GetWindowPlacement(hWnd, ref placement);
           if (placement.showCmd != SW_NORMAL)
           {
                placement.showCmd = SW_RESTORE;

                SetWindowPlacement(hWnd, ref placement);
                SetForegroundWindow(hWnd);
            }
       }
                return;
     }
    Application.Run(new Form1());
    GC.KeepAlive(Mut);
}

private const int SW_NORMAL = 1;
private const int SW_RESTORE = 9;

[DllImport("User32", EntryPoint = "FindWindow")]
static extern IntPtr FindWindow(string className, string windowName);

[DllImport("User32", EntryPoint = "SendMessage")]
private static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);

[DllImport("User32", EntryPoint = "SetForegroundWindow")]
private static extern bool SetForegroundWindow(IntPtr hWnd);

[DllImport("User32", EntryPoint = "SetWindowPlacement")]
private static extern bool SetWindowPlacement(IntPtr hWnd, [In] ref WINDOWPLACEMENT lpwndpl);

[DllImport("User32", EntryPoint = "GetWindowPlacement")]
private static extern bool GetWindowPlacement(IntPtr hWnd, [In] ref WINDOWPLACEMENT lpwndpl);

private struct POINTAPI
{
    public int x;
    public int y;
}

private struct RECT
{
    public int left;
    public int top;
    public int right;
    public int bottom;
}

private struct WINDOWPLACEMENT
{
    public int length;
    public int flags;
    public int showCmd;
    public POINTAPI ptMinPosition;
    public POINTAPI ptMaxPosition;
    public RECT rcNormalPosition;
}

Ebook Download
View all
Learn
View all