How to make Singleton Application in c#


 Step1. Create a sub class inside class


        static class NativeMethods



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



            public static extern bool SetForegroundWindow(IntPtr hWnd);



            public static extern bool EnumWindows(EnumWindowsProcDel lpEnumFunc,

                Int32 lParam);  


            public static extern int GetWindowThreadProcessId(IntPtr hWnd,

                ref Int32 lpdwProcessId);  


            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);



            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),


                    return false;



            return true;



Step 4. Execute the method as below


If (IsOnlyProcess("Hidden"))





Leave a Reply

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

You are commenting using your 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