Winform实例不允许直接启动,不允许重复启动的方法

Step1:修改Program,可以实现仅允许启动一次程序实例,且不可直接启动

static class Program
    {
        private static System.Threading.Mutex mutex;
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            mutex = new System.Threading.Mutex(true, "FTZNFView");  //此为程序进程名,启动时检测是否已有这个进程,如果已有则不启动
            if (mutex.WaitOne(0, false))
            {
                if (args.Length <= 0)
                {
                    DialogResult dr = MessageBox.Show("无法直接启动本程序,请咨询开发人员!");
                    if (dr == DialogResult.OK)
                        Application.Exit();
                }
                if (args.Length == 1)
                {
                    if (args[0] == "吾等烟雨")  //这个字符串可以理解为启动秘钥,在程序启动时传入这个秘钥,程序才能启动
                    {
                        Application.Run(new FTZNFView(args));
                    }
                    else
                    {
                        MessageBox.Show("启动参数不正确,请咨询开发人员!");
                        Application.Exit();
                    }
                }
            }
            else
            {
                MessageBox.Show("程序已经在运行!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                Application.Exit();
            }
            
        }
    }

Step2

需要调用该程序时,定义一个方法

        public bool StartProcess(string filename, string[] args)
        {
            try
            {
                string s = "";
                foreach (string arg in args)
                {
                    s = s + arg + " ";
                }
                s = s.Trim();
                Process myprocess = new Process();
                ProcessStartInfo startInfo = new ProcessStartInfo(filename, s);
                myprocess.StartInfo = startInfo;

                //通过以下参数可以控制exe的启动方式,具体参照 myprocess.StartInfo.下面的参数,如以无界面方式启动exe等
                myprocess.StartInfo.UseShellExecute = false;
                myprocess.Start();
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show("启动应用程序时出错!原因:" + ex.Message);
            }
            return false;
        }
        private void btn1_Click(object sender, System.EventArgs e)
        {
            string[] arg = new string[1];
            arg[0] = "吾等烟雨";
            StartProcess("FTZNFView",arg);
        }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值