zoukankan      html  css  js  c++  java
  • WINFORM 只能运行一个实例问题

    WINFROM 只能运行一个实例 目前网上比较多的又2种方法

    第一种:Mutex

    /// <summary>
            /// 应用程序的主入口点。
            /// </summary>
            [STAThread]
            static void Main()
            {
                //声明互斥体。
                Mutex mutex = new Mutex(false, "ThisShouldOnlyRunOnce ");
                //判断互斥体是否使用中。
                bool Running = !mutex.WaitOne(0, false);

                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);

                if (!Running)
                    Application.Run(new LoginForm());
                else
                    MessageBox.Show("应用程序已经启动! ");
            }

    第二种:判断进程

      private static Process RunningInstance()
            {
                Process current = Process.GetCurrentProcess();
                Process[] processes = Process.GetProcessesByName(current.ProcessName);
                //遍历与当前进程名称相同的进程列表  
                foreach (Process process in processes)
                {
                    //如果实例已经存在则忽略当前进程  
                    if (process.Id != current.Id)
                    {
                        //保证要打开的进程同已经存在的进程来自同一文件路径
                        if (Assembly.GetExecutingAssembly().Location.Replace("/", "//") == current.MainModule.FileName)
                        {
                            //返回已经存在的进程
                            return process;

                        }
                    }
                }
                return null;
            }

    用2种方式分别测试了下,发现第二种判断进程是完全可以的,第一种在多用户多窗口模式下会判断失败。

  • 相关阅读:
    jvm09
    jvm08
    jvm07
    求解最长公共子序列问题
    归并排序
    求解N皇后问题
    快速排序算法
    求解0/1背包问题
    求解全排列问题
    求解最大连续子序列和问题
  • 原文地址:https://www.cnblogs.com/merray/p/2749137.html
Copyright © 2011-2022 走看看