c# - Windows 窗体应用程序命令行参数

标签 c# winforms command-line-arguments

我通过 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 时它都会出错 ex

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

最佳答案

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

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 消息等。

关于c# - Windows 窗体应用程序命令行参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19965311/

相关文章:

c# - 在 Windows 窗体应用程序中单击按钮时隐藏窗体并显示另一个窗体

c# - 使用 Windows 形式的命令行参数

c# - 在类库项目中实现 IValueConverter

c# - 在 BindingSource 中组合多个列表

c# - .net 4.5 中异步和同步的区别

c# - 如何手动滚动面板?

python-2.7 - Python 中的多个命令行参数

c - 尝试检查命令行参数时出现段错误(在 C 中)

c# - 如何使用核心服务在 Tridion 2011 中创建新用户?

c# - WebForms 相当于 MVC 的 "return Content()"?