2015年3月31日 星期二

[C#] How to prevent our program from being executed twice?

When our program is running, and then the user press the execution file again,
we wish that it will show up the window of program being executed instead of forking a new program. 
To achieve that, we just need to check the status in program.cs:
static void Main(){           
    if (frmMain.AlreadyRunning())
    {
      return;
    }

    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    Application.Run(new frmMain());
}
The  function AlreadyRunning() is declared in frmMain.cs.
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))
                        {
                            MessageBox.Show("Already running", "", MessageBoxButtons.OK);
                            ShowWindowAsync(hWnd, swRestore);                            
                        }

                        // bring it to the foreground
                        SetForegroundWindow(hWnd);
                        
                        break;
                    }
                }
                return true;
            }

            return false;
        }

沒有留言:

張貼留言