如何在winform中使用参数打开一个新的winform

问题描述 投票:0回答:1

我想捕获一个try/catch未捕获的错误,并退出当前的winform,然后使用参数打开一个新的winform,但该参数从未转移到Main()。

[STAThread]
static void Main(string[] args)
{
    var logger = NLog.LogManager.Setup().LoadConfigurationFromFile().GetCurrentClassLogger();
logger.Debug("init main");

   ApplicationConfiguration.Initialize();
   AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

  if(args.Length > 0 && args[0]== "/restart")             
  {
      Application.Run(new Form1(true));
  }
  else
  {
      Application.Run(new Form1(false));

  }
  LogManager.Shutdown();
}

private static void CurrentDomain_UnhandledException(object sender, 
 UnhandledExceptionEventArgs e)
{
  Exception ex = (Exception)e.ExceptionObject;
  var logger = NLog.LogManager.GetCurrentClassLogger();
  logger.Error("CurrentDomain_UnhandledException: " + ex.Message+": "+ex.StackTrace);

  Process.Start(Application.ExecutablePath, "restart");       
  Application.Exit();
}

但是当创建新的 winform 时,参数“restart”从未被传递到 Main() 。

谁能告诉我为什么?

c# winforms
1个回答
0
投票
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

        string[] args = Environment.GetCommandLineArgs();

        int idx = Array.IndexOf(args, "restart");

        if (idx > -1)
        {
            MessageBox.Show(args[idx]);
            Application.Run(new Form1("2"));
        }
        else
        {
            Application.Run(new Form1("1"));
        }

运作良好。

© www.soinside.com 2019 - 2024. All rights reserved.