Friday, September 9, 2011

Often I Prefer single instance application on Form

    internal static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>


        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool SetForegroundWindow(IntPtr hWind);

        [DllImport("user32.dll")]
        private static extern bool ShowWindowAsync(IntPtr hWind, int cmd);


        [STAThread]
        private static void Main()
        {
            bool mutexWasCreated;
            var mut = new Mutex(true, "{..arun@darkside..}", out mutexWasCreated);
            if (mutexWasCreated)
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new Form1());
                mut.ReleaseMutex();
            }
            else
            {
                Process current = Process.GetCurrentProcess();
                for (int index = 0; index < Process.GetProcessesByName(current.ProcessName).Length; index++)
                {
                    Process process = Process.GetProcessesByName(current.ProcessName)[index];
                    if (process.Id == current.Id) continue;
                    SetForegroundWindow(process.MainWindowHandle);
                    ShowWindowAsync(process.MainWindowHandle, 9);
                    break;
                }
            }
        }
    }

No comments :