【问题标题】:How do I pass command-line arguments to a WinForms application?如何将命令行参数传递给 WinForms 应用程序?
【发布时间】:2010-11-13 20:27:01
【问题描述】:

我有两个不同的 WinForms 应用程序,AppA 和 AppB。两者都运行 .NET 2.0。

在 AppA 中,我想打开 AppB,但我需要将命令行参数传递给它。如何使用我在命令行中传递的参数?

这是我目前在 AppB 中的主要方法,但我认为您无法更改它?

  static void main()
  {
  }

【问题讨论】:

    标签: c# winforms command-line


    【解决方案1】:

    假设您需要开发一个程序,您需要通过该程序传递两个参数。首先,您需要打开 Program.cs 类并在 Main 方法中添加参数,如下所示,并将这些参数传递给 Windows 窗体的构造函数。

    static class Program
    {    
       [STAThread]
       static void Main(string[] args)
       {            
           Application.EnableVisualStyles();
           Application.SetCompatibleTextRenderingDefault(false);
           Application.Run(new Form1(args[0], Convert.ToInt32(args[1])));           
       }
    }
    

    在 windows 窗体类中,添加一个参数化构造函数,该构造函数接受来自 Program 类的输入值,如下所示。

    public Form1(string s, int i)
    {
        if (s != null && i > 0)
           MessageBox.Show(s + " " + i);
    }
    

    要对此进行测试,您可以打开命令提示符并转到放置此 exe 的位置。给出文件名,然后给出参数 1 参数 2。例如,见下文

    C:\MyApplication>Yourexename p10 5
    

    从上面的 C# 代码中,它会提示一个值为 p10 5 的消息框。

    【讨论】:

      【解决方案2】:
      static void Main(string[] args)
      {
        // For the sake of this example, we're just printing the arguments to the console.
        for (int i = 0; i < args.Length; i++) {
          Console.WriteLine("args[{0}] == {1}", i, args[i]);
        }
      }
      

      然后参数将存储在args 字符串数组中:

      $ AppB.exe firstArg secondArg thirdArg
      args[0] == firstArg
      args[1] == secondArg
      args[2] == thirdArg
      

      【讨论】:

      • 输入:“whatever.exe -v foo /lol nisp”。输出:args[0] = "-v"; args[1] = "foo"; args[2] = "/大声笑"; args[3] = "nisp";还有什么比这更容易的?
      • 不敢相信我在整整一年之后多次看到'string[] args',但直到现在我才想到它!哈哈
      • 看来args[0]是运行的应用程序的完整路径和exe名称,args[1]是第一个参数。
      【解决方案3】:

      这可能不是每个人都喜欢的解决方案,但我喜欢 Visual Basic 中的应用程序框架,即使在使用 C# 时也是如此。

      添加对Microsoft.VisualBasic的引用

      创建一个名为 WindowsFormsApplication 的类

      public class WindowsFormsApplication : WindowsFormsApplicationBase
      {
      
          /// <summary>
          /// Runs the specified mainForm in this application context.
          /// </summary>
          /// <param name="mainForm">Form that is run.</param>
          public virtual void Run(Form mainForm)
          {
              // set up the main form.
              this.MainForm = mainForm;
      
              // Example code
              ((Form1)mainForm).FileName = this.CommandLineArgs[0];
      
              // then, run the the main form.
              this.Run(this.CommandLineArgs);
          }
      
          /// <summary>
          /// Runs this.MainForm in this application context. Converts the command
          /// line arguments correctly for the base this.Run method.
          /// </summary>
          /// <param name="commandLineArgs">Command line collection.</param>
          private void Run(ReadOnlyCollection<string> commandLineArgs)
          {
              // convert the Collection<string> to string[], so that it can be used
              // in the Run method.
              ArrayList list = new ArrayList(commandLineArgs);
              string[] commandLine = (string[])list.ToArray(typeof(string));
              this.Run(commandLine);
          }
      
      }
      

      将您的 Main() 例程修改为如下所示

      static class Program
      {
      
          [STAThread]
          static void Main()
          {
              Application.EnableVisualStyles();
              Application.SetCompatibleTextRenderingDefault(false);
      
              var application = new WindowsFormsApplication();
              application.Run(new Form1());
          }
      }
      

      此方法提供了一些额外的有用功能(如 SplashScreen 支持和一些有用的事件)

      public event NetworkAvailableEventHandler NetworkAvailabilityChanged;d.
      public event ShutdownEventHandler Shutdown;
      public event StartupEventHandler Startup;
      public event StartupNextInstanceEventHandler StartupNextInstance;
      public event UnhandledExceptionEventHandler UnhandledException;
      

      【讨论】:

        【解决方案4】:

        为您的 winforms 应用程序使用 args 的最佳方式是使用

        string[] args = Environment.GetCommandLineArgs();
        

        您可以将此与 enum 的使用结合起来,以巩固整个代码库中数组的使用。

        “而且你可以在你的应用程序的任何地方使用它,你不仅仅是 仅限于在 main() 方法中使用它,例如在控制台中 申请。”

        发现于:HERE

        【讨论】:

        • 数组的第一个元素包含执行程序的文件名。如果文件名不可用,则第一个元素等于 String.Empty。其余元素包含在命令行中输入的任何附加标记。
        • @docesam 这对我帮助很大,谢谢!想知道为什么它一直试图将程序本身作为文本加载。
        • 经过多年的 C# 开发,我从不知道这种方法存在。不错。
        • 使用这种方法与发送参数main(string[] args)相比有什么好处吗?
        【解决方案5】:

        你使用这个签名:(在 c# 中)static void Main(string[] args)

        这篇文章也可能有助于解释 main 函数在编程中的作用: http://en.wikipedia.org/wiki/Main_function_(programming)

        这里有一个小例子:

        class Program
        {
            static void Main(string[] args)
            {
                bool doSomething = false;
        
                if (args.Length > 0 && args[0].Equals("doSomething"))
                    doSomething = true;
        
                if (doSomething) Console.WriteLine("Commandline parameter called");
            }
        }
        

        【讨论】:

          【解决方案6】:

          您可以通过访问 Environment.CommandLine 属性来获取任何 .Net 应用程序的命令行。它将命令行作为单个字符串,但解析出您正在寻找的数据应该不是非常困难。

          拥有一个空的 Main 方法不会影响此属性或另一个程序添加命令行参数的能力。

          【讨论】:

          • 或者使用 Environment.GetCommandLineArgs() 返回参数的字符串数组,就像 Main(string[] args)
          猜你喜欢
          • 1970-01-01
          • 2010-09-30
          • 2020-01-01
          • 2020-12-13
          • 2021-05-21
          • 1970-01-01
          • 2013-07-12
          • 2011-05-20
          相关资源
          最近更新 更多