Windows form application command line arguments

2020-03-04 07:01发布

问题:

I have searched through Google and here found many examples but I can't seem to get my Windows Form application to run and take arguments form the command line. I really want to have the option of scheduling the application without having a console version. But every time I setup the cmd line arguments it errors out with a CLR20r3 error.

static void Main(string[] args)
{
   if(args != null && args.Length > 0)
   {
      /*
      * arg[1] = Backup Location *require
      * arg[2] = Log File - Enable if present *optional
      * arg[3] = Debug Messages - Enabled if present *optional
      * arg[4] = Backup Type - Type to perform *required
      */

   }
   else
   {
     Application.EnableVisualStyles();
     Application.SetCompatibleTextRenderingDefault(false);
     Application.SetUnhandledExceptionMode(UnhandledExceptionMode.Automatic);
     Application.Run(new Form1());
   }
}

Anytime I try to pass an arg it errors ex

myapp.exe "C:\Backup\" => CLR20r3

回答1:

This is an example of the startup code I use in a project that runs as a form app or as a formless app depending on command line arguments.

using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace BuildFile
{
  static class Program
  {
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
      int ABCFile = -1;
      string[] args = Environment.GetCommandLineArgs();
      if ((args.Length > 1) && (args[1].StartsWith("/n")))
      {
            ... unrelated details omiited
            ABCFile = 1;
        }
      }

      if (ABCFile > 0)
      {
        var me = new MainForm(); // instantiate the form
        me.NoGui(ABCFile); // call the alternate entry point
        Environment.Exit(0);
      }
      else
      {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new MainForm());
      }
    }
  }
}

Note this only works because nothing in my alternative entry point depends on events, etc. that are provided by the runtime environment Application.Run() method which includes handling windows messages, etc.