如何判断一个windows应用程序的实例已经启动?防止用户启动多个该程序的实例!请给出完整代码!

解决方案 »

  1.   


    可以使用互斥体Mutex类型完成此功能。见如下代码:   
              [STAThread]   
              public   static   void   Main(string[]   args)     
              {   
                        //声明互斥体。   
                        Mutex   mutex   =   new   Mutex(false,   "ThisShouldOnlyRunOnce");   
                        //判断互斥体是否使用中。   
                        bool   Running   =   !mutex.WaitOne(0,   false);   
                        if   (!   Running)   
                                Application.Run(new   FormLogin());   
                        else   
                                MessageBox.Show("应用程序已经启动!");   
              }   
      

  2.   

    using System;
    using System.Collections.Generic;
    using System.Windows.Forms;
    using System.Diagnostics;namespace Instance
    {
        static class Program
        {
            /// <summary>
            /// 应用程序的主入口点。
            /// </summary>
            [STAThread]
            static void Main()
            {
                foreach (Process p in Process.GetProcesses ())
                {
                    if (p.ProcessName == Process.GetCurrentProcess().ProcessName)
                    {
                        return;
                    }
                }
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new Form1());
            }
        }
    }
      

  3.   

    修正一下
    using System;
    using System.Collections.Generic;
    using System.Windows.Forms;
    using System.Diagnostics;namespace GUI试验
    {
        static class Program
        {
            /// <summary>
            /// 应用程序的主入口点。
            /// </summary>
            [STAThread]
            static void Main()
            {
                foreach (Process p in Process.GetProcesses ())
                {
                    if (p.ProcessName == Process.GetCurrentProcess().ProcessName && p.Id!=Process.GetCurrentProcess ().Id )
                    {
                        return;
                    }
                }
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new Form1());
            }
        }
    }
      

  4.   

    最好用mutex判断,用processname判断的话,如果更改了程序名字也可以多次打开的