使用内核对象Mutex可以防止同一个进程运行两次

用互斥法实现防止程序重复运行,使用内核对象Mutex可以防止同一个进程运行两次。注意:是名称相同的进程,而不是exe,因为exe程序可以改名。

在Program.cs中修改

首先添加using System.Threading;引用

然后原内容改为下面所示

    static class Program

    {

        private static Mutex myMutex;

        private static bool requestInitialOwnership = true;

        private static bool mutexWasCreated;

        /// <summary>

        /// The main entry point for the application.

        /// </summary>

        [STAThread]

        static void Main()

        {

            //原来代码

            //Application.EnableVisualStyles();

            //Application.SetCompatibleTextRenderingDefault(false);

            //Application.Run(new Form1());



            //新代码

            myMutex = new Mutex(requestInitialOwnership, "CanbeAnything ", out mutexWasCreated);

            if (mutexWasCreated)

            {

                Application.Run(new Form1());

                myMutex.WaitOne();

            }

        }

    }

 

你可能感兴趣的:(对象)