C# WINFORM判断程序已经运行,且只能运行一个实例,只运行一个进程

 

 

判断程序是否已经运行,使程序只能运行一个实例:

方法1:

//这种检测进程的名的方法,并不绝对有效。因为打开第一个实例后,将运行文件改名后,还是可以运行第二个实例.

        private static bool isAlreadyRunning()
        {
            bool b = false;
            Process[] mProcs = Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName);
            if (mProcs.Length > 1) {
                b = true;
            }
            return b;
        }

方法2:

//线程互斥

        static void Main()
        {
            bool canCreateNew;
            Mutex m = new Mutex(true, "DRM", out canCreateNew);
            if (canCreateNew)
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new DRM());
                m.ReleaseMutex();
            }
            else {
                MessageBox.Show("程序已经运行!");
            }

        }

 

posted on 2011-11-09 16:49  老有所依  阅读(339)  评论(0)    收藏  举报

导航