• 程序只运行一次的方法


    方法一:使用Mutex来进行

    1. 首先要添加如下的namespace:

    using System.Threading;

    2. 修改系统Main函数,大致如下:

            bool bCreatedNew;

          

            //Create a new mutex using specific mutex name

            Mutex m =new Mutex( false, "myUniqueName", out bCreatedNew );

            if( bCreatedNew )

                Application.Run(new yourFormName());

    如上面编码就可以了,要注意的一点是,在给Mutex起名字的时候,不要太简单,以防止和其他程序的Mutex重复,从而达不到所预想的效果。

    方法二:使用Process来进行

    1. 首先要添加如下的namespace:

    using System.Diagnostics;

    using System.Reflection;

    2. 添加如下函数:

            public static Process RunningInstance()

            {

                Process current = Process.GetCurrentProcess();

                Process[] processes = Process.GetProcessesByName(current.ProcessName);

                //Loop through the running processes in with the same name

                foreach (Process process in processes)

                {

                    //Ignore the current process

                    if (process.Id != current.Id)

                    {

                        //Make sure that the process is running from the exe file.

                        if (Assembly.GetExecutingAssembly().Location.Replace("/", "\\") == current.MainModule.FileName)

                        {

                            //Return the other process instance.

                            return process;

                        }

                    }

                }

                //No other instance was found, return null.

                return null;

            }

    3. 修改系统Main函数,大致如下:

                if( RunningInstance() == null )

                    Application.Run(new yourFormName());

    如上面编码就可以了,要注意的一点是,在判断进程模块文件名是否相等这部分的代码,是可选的。如果当前的程序在文件系统中只存在一个的话,以上的方法是可以的;否则不要删除这部分的代码。

  • 相关阅读:
    Codeforces Round #325 (Div. 2) F:(meet in the middle)
    Educational Codeforces Round 3:E (MST+树链剖分+RMQ)
    Educational Codeforces Round 3:D. Gadgets for dollars and pounds(二分答案+贪心)
    CodeForce 484B:(最大余数)
    CodeForce 540C:(DFS)
    HDU 1010:(DFS)
    Poj1741-Tree(树分治)
    uva10245-The Closest Pair Problem(平面上的点分治)
    hdu1561-The more, The Better(树形dp)
    hdu2196-Computer(树形dp)
  • 原文地址:https://www.cnblogs.com/houzhitong/p/2398736.html
Copyright © 2020-2023  润新知