C# Singleton Application

There are several option that can be used to create singleton application.

Option 1.

 


///
<summary>


/// Supporting function for “singleton” functionality


///
</summary>


///
<returns></returns>


public
static
Process IsRunningInstance()

{


Process current = Process.GetCurrentProcess();


Process[] processes = Process.GetProcessesByName(current.ProcessName);

 


//Loop through the running processes in with the same name


foreach (Process process in processes)

{


//Ignore the current process


if (process.Id != current.Id)

{


//Make sure that the process is running from the exe file.


if (Assembly.GetExecutingAssembly().Location.

Replace(“/”, “\\”) == current.MainModule.FileName)

{


//Return the other process instance.


return process;

 

}

}

}


//No other instance was found, return null.


return
null;

}

 

Application code (in constructor of the main form):


// Singleton verification – exit if application is already started

 


if (RunningInstance() != null)

{


string singletonRedirectUrl = util.GetAppSetting(“singletonRedirectUrl”, “0”);


string redirectPage = DownloadWebPage(singletonRedirectUrl);

 


//MessageBox.Show(“redirected”);

 

log.Info(“Duplicate instance detected. Exiting application.”);

 

System.Environment.Exit(1);

}

 

Option 2.

This sample is based on:

http://blog.billsdon.com/2011/10/c-sharp-check-if-application-is-already-running-then-set-focus/

using System;

using System.Diagnostics;

using System.Runtime.InteropServices;

 
 

/// ————————————————————————————————-

/// <summary> Application Running Helper. </summary>

/// ————————————————————————————————-

public static class ApplicationRunningHelper

{

    [DllImport(“user32.dll”)]

    private static extern

        bool SetForegroundWindow(IntPtr hWnd);

    [DllImport(“user32.dll”)]

    private static extern

        bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);

    [DllImport(“user32.dll”)]

    private static extern

        bool IsIconic(IntPtr hWnd);

 
 

    /// ————————————————————————————————-

    /// <summary> check if current process already running. if running, set focus to existing process and

    ///           returns <see langword=”true”/> otherwise returns <see langword=”false”/>. </summary>

    /// <returns> <see langword=”true”/> if it succeeds, <see langword=”false”/> if it fails. </returns>

    /// ————————————————————————————————-

    public static bool AlreadyRunning()

    {

        /*

        const int SW_HIDE = 0;

        const int SW_SHOWNORMAL = 1;

        const int SW_SHOWMINIMIZED = 2;

        const int SW_SHOWMAXIMIZED = 3;

        const int SW_SHOWNOACTIVATE = 4;

        const int SW_RESTORE = 9;

        const int SW_SHOWDEFAULT = 10;

        */

        const int swRestore = 9;

 
 

        var me = Process.GetCurrentProcess();

        var arrProcesses = Process.GetProcessesByName(me.ProcessName);

 
 

        if (arrProcesses.Length > 1)

        {

            for (var i = 0; i < arrProcesses.Length; i++)

            {

                if (arrProcesses[i].Id != me.Id)

                {

                    // get the window handle

                    IntPtr hWnd = arrProcesses[i].MainWindowHandle;

 
 

                    // if iconic, we need to restore the window

                    if (IsIconic(hWnd))

                    {

                        ShowWindowAsync(hWnd, swRestore);

                    }

 
 

                    // bring it to the foreground

                    SetForegroundWindow(hWnd);

                    break;

                }

            }

            return true;

        }

 
 

        return false;

    }

}

Advertisements