Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

How to Receive Execution Arguments on a C# WinForms Application?

0.00/5 (No votes)
24 Nov 2011 1  
How to receive execution arguments for a C# WinForms application

The below code that illustrates how to receive arguments for a WinForms Application. The example expects two arguments and validates that they are converted properly. If the appropriate arguments are sent, these are stored in a public class named GlobalVars.

[STAThread]
 static void Main( string[] MyArgs)
 {
     Application.EnableVisualStyles();
     Application.SetCompatibleTextRenderingDefault(false);

     if (MyArgs.Length == 0 || MyArgs.Length < 2)
     {
        MessageBox.Show(
        "Please specify Parm1 and Parm2 as Arguments in order to
         Proceed.",
        "YourAppTitle", MessageBoxButtons.OK, MessageBoxIcon.Error);
        Application.Exit();
        return;
      }
      else
      {
         try
         {
            GlobalVars lGlobalVars = new GlobalVars();
            lGlobalVars.gOrderSkey = Int64.Parse(MyArgs[0]);
            lGlobalVars.gShipmentNo = Int64.Parse(MyArgs[1]);
          }
          catch (Exception Ex)
          {
             MessageBox.Show(
          "Invalid Parm1 and/or Parm2 Arguments. Please verify. \rError: "
          + Ex.Message, "YourAppTitle",
          MessageBoxButtons.OK, MessageBoxIcon.Error);
          Application.Exit();
          return;
          }
          Application.Run(new Form1());
      }
}

Notice the "\n" to break down the MessageBox in two lines. It is a nice little trick that I often forget.

Hope this helps,
Will

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here