C# 禁止windows程序重复运行的两种基本方法

一般有两种方法,我是用的是第一种

方法1:

在项目的第一个窗体的启动事件中 如form1_load() 中添加如下语句


#region 判断系统是否已启动

            System.Diagnostics.Process[] myProcesses = System.Diagnostics.Process.GetProcessesByName("这里是你的程序进程名");//获取指定的进程名  
            if (myProcesses.Length > 1) //如果可以获取到知道的进程名则说明已经启动
            {
                MessageBox.Show("程序已启动!");
                Application.Exit();              //关闭系统
            }
         

#endregion


===================================================================================
好了 这样就可以达到防止用户第二次启动此程序的目的了
当然你也可以把它编辑成一个类 或生成一个dll文件 调用它。


方法2.

在项目的启动引导文件 Program.cs中加入判断语句

using System.Linq;
using System.Windows.Forms;

namespace XiaoZhiSoft
{
    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            bool isRuned;
            System.Threading.Mutex mutex = new System.Threading.Mutex(true, "OnlyRunOneInstance", out isRuned);
            if (isRuned)
            {

                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new Form1());
                mutex.ReleaseMutex();
            }
            else
            {
                MessageBox.Show("程序已启动!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
    }
}

posted @ 2012-10-24 15:35  北冥子  阅读(13614)  评论(2编辑  收藏  举报