怎样重启WinForm/WPF程序

19 篇文章 0 订阅
2 篇文章 0 订阅

怎样重启WinForm/WPF程序

可以使用如下代码
Application.ExitThread(); //退出主线程,并关闭所有窗体
System.Diagnostics.Process.Start(System.Reflection.Assembly.GetExecutingAssembly().Location);开启新进程

当然如果代码没有在主线程中,还要使用this.BeginInvoke(),或this.Invoke()来执行,避免跨线程异常

this.BeginInvoke((MethodInvoker)delegate()
                {
                   
                    Application.ExitThread();
                  
                }
                  );
 System.Diagnostics.Process.Start(System.Reflection.Assembly.GetExecutingAssembly().Location);

 

在WPF中,类似功能代码如下:

使用了this.Dispatcher代替了this,

Application.Current.Shutdown();代替了WinForm中的ExitThread();


  this.Dispatcher.Invoke((ThreadStart)delegate()
            {
                Application.Current.Shutdown();
            }
              );
 System.Diagnostics.Process.Start(System.Reflection.Assembly.GetExecutingAssembly().Location);


17:43 2014/7/30:

为了避免一个程序只能运行一个实例,我们常常用以下类似的方法来查询当前运行的程序进程

   public static bool GetRunningProcess()
        {
            Process current = Process.GetCurrentProcess();
            Process[] processes = Process.GetProcessesByName(current.ProcessName);          
            return (processes.Length > 1); 
        }


由于是在本进程中,再次生成本进程,可能导致新进程运行后,旧进程未完全释放的情况,

会导致使用上面的方法查询到两个进程.因此我们可以 将

 System.Diagnostics.Process.Start(System.Reflection.Assembly.GetExecutingAssembly().Location);

改为

System.Diagnostics.Process.Start(System.Reflection.Assembly.GetExecutingAssembly().Location,"anyWord");

并且在Main方法中进行排除

  static void Main(string[] args)
        {

            if (args != null && args.Length > 0)
            {
               //参数为 "anyWord",不用判断进程数量
            }
            else
            {
                if (GetRunningProcess())
                {
                    MessageBox.Show("应用程序实例已经在运行!");
                    Environment.Exit(Environment.ExitCode);
                }
            }

            try
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new Form1());

            }
            catch (Exception ex)
            {
               //
            } 
        }


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值