【问题标题】:Windows form application command line argumentsWindows 窗体应用程序命令行参数
【发布时间】:2013-11-26 17:38:14
【问题描述】:

我已经通过 Google 进行了搜索,在这里找到了很多示例,但我似乎无法让我的 Windows 窗体应用程序运行并从命令行获取参数。我真的希望可以选择在没有控制台版本的情况下安排应用程序。但每次我设置 cmd 行参数时,都会出现 CLR20r3 错误。

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());
   }
}

任何时候我尝试传递一个 arg 它都会出错

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

【问题讨论】:

  • 这真的是你所有的代码吗?根据您发布的内容,我没有看到您可以传递参数的任何地方。
  • 您收到什么异常?您可能可以在事件查看器中找到它。
  • @Brian 不是我所有的代码只是它的开始,以确保我做对了
  • 您是否尝试过调试应用程序?您可以告诉您的 IDE 传递命令行参数。您还可以在尝试解析之前将 args 的内容转储到日志文件中,以确认应用正在接收您认为应该接收的内容。
  • System.NullReferenceException 因为 Main 中的 args 不适用于 Windows 窗体应用程序,您应该使用 string[] args = Environment.GetCommandLineArgs()

标签: c# winforms command-line-arguments


【解决方案1】:

这是我在项目中使用的启动代码示例,该项目根据命令行参数作为表单应用程序或无表单应用程序运行。

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());
      }
    }
  }
}

请注意,这仅适用,因为我的替代入口点中的任何内容都不依赖于运行时环境 Application.Run() 方法提供的事件等,其中包括处理 Windows 消息等。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-08
    • 2013-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-02
    相关资源
    最近更新 更多