How to make Singleton Application in c#

 

 Step1. Create a sub class inside class

 

        static class NativeMethods

        {

            [DllImport("user32.dll")]

            public static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);

 

            [DllImport("user32.dll")]

            public static extern bool SetForegroundWindow(IntPtr hWnd);

 

            [DllImport("user32.dll")]

            public static extern bool EnumWindows(EnumWindowsProcDel lpEnumFunc,

                Int32 lParam);  

            [DllImport("user32.dll")]

            public static extern int GetWindowThreadProcessId(IntPtr hWnd,

                ref Int32 lpdwProcessId);  

            [DllImport("user32.dll")]

            public static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString,

                Int32 nMaxCount); 

            public const int SW_SHOWNORMAL = 1;

        }  

Step 2. Declare a Delegate  

public delegate bool EnumWindowsProcDel(IntPtr hWnd, Int32 lParam);  

Step 3. Create a two function  

static private bool EnumWindowsProc(IntPtr hWnd, Int32 lParam)

        {

            int processId = 0; 

            NativeMethods.GetWindowThreadProcessId(hWnd, ref processId);  

            StringBuilder caption = new StringBuilder(1024);

            NativeMethods.GetWindowText(hWnd, caption, 1024);  

            if (processId == lParam && (caption.ToString().IndexOf(_requiredString,

                StringComparison.OrdinalIgnoreCase) != -1))

            {

                NativeMethods.ShowWindowAsync(hWnd, NativeMethods.SW_SHOWNORMAL);

                NativeMethods.SetForegroundWindow(hWnd);

            }

            return true  

     }  

        static public bool IsOnlyProcess(string forceTitle)

        {

            _requiredString = forceTitle;

            foreach (Process proc in Process.GetProcessesByName("HidenApp"))

            {

                if (proc.Id != Process.GetCurrentProcess().Id)

                {

                    NativeMethods.EnumWindows(new EnumWindowsProcDel(EnumWindowsProc),

                        proc.Id);

                    return false;

                }

            }

            return true;

        }

 

Step 4. Execute the method as below

 

If (IsOnlyProcess("Hidden"))

{

} 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s