winform程序在当前会话只允许启动一个的方法

来源:互联网 发布:ios内存管理及优化 编辑:程序博客网 时间:2024/05/18 00:10

以下代码加在Program类中:

static class Program
    {
        private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            if (!IsSingle())
            {
                MessageBox.Show(
                  "应用程序已经运行于当前会话或者本机的其它会话中!\r\n或隐藏于系统托盘区域!",
                  "图片路径检测",
                  MessageBoxButtons.OK,
                  MessageBoxIcon.Warning
                  );
                return;
            }

            try
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new FrmCKImagePath());
            }
            catch (Exception e)
            {
                if (log.IsInfoEnabled) log.Info(e.Message + "***" + e.StackTrace);
                throw;
            }
        }

        private static System.Threading.Mutex m_mutex;//互斥体


        /// <summary>
        /// 判断应用程序是否在所有会话中单独运行
        /// </summary>
        /// <returns></returns>
        private static bool IsSingle()
        {
            bool single = false;
            m_mutex = new System.Threading.Mutex(true, @"Global\CheckImagePath", out single);
            return single;
        }
    }

 

原创粉丝点击