如何将命令行参数传递给WinForms应用程序?

时间:2022-03-22 04:17:02

I have two different WinForms applications, AppA & AppB. Both are running .NET 2.0.

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

In AppA I want to open AppB, but I need to pass command-line arguments to it. How do I consume the arguments that I pass in the command line?

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

This is my current main method in AppB, but I don't think you can change this?

这是我目前在AppB中的主要方法,但我认为你不能改变它吗?

  static void main()
  {
  }

6 个解决方案

#1


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

The arguments will then be stored in the args string array:

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

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

#2


The best way to work with args for your winforms app is to use

使用winforms应用程序的args的最佳方法是使用

string[] args = Environment.GetCommandLineArgs();

You can probably couple this with the use of an enum to solidify the use of the array througout your code base.

您可以将此与使用枚举相结合,以通过代码库巩固阵列的使用。

"And you can use this anywhere in your application, you aren’t just restricted to using it in the main() method like in a console application."

“你可以在应用程序的任何地方使用它,你不仅限于在main()方法中使用它,就像在控制台应用程序中一样。”

Found at:HERE

#3


You can grab the command line of any .Net application by accessing the Environment.CommandLine property. It will have the command line as a single string but parsing out the data you are looking for shouldn't be terribly difficult.

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

Having an empty Main method will not affect this property or the ability of another program to add a command line parameter.

具有空Main方法不会影响此属性或其他程序添加命令行参数的能力。

#4


Consider you need to develop a program through which you need to pass two arguments. First of all, you need to open Program.cs class and add arguments in the Main method as like below and pass these arguments to the constructor of the Windows form.

考虑您需要开发一个程序,您需要通过该程序传递两个参数。首先,您需要打开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])));           
   }
}

In windows form class, add a parameterized constructor which accepts the input values from Program class as like below.

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

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

To test this, you can open command prompt and go to the location where this exe is placed. Give the file name then parmeter1 parameter2. For example, see below

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

C:\MyApplication>Yourexename p10 5

From the C# code above, it will prompt a Messagebox with value p10 5.

从上面的C#代码,它将提示值为p10 5的Messagebox。

#5


You use this signature: (in c#) static void Main(string[] args)

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

This article may help to explain the role of the main function in programming as well: http://en.wikipedia.org/wiki/Main_function_(programming)

本文也可以帮助解释主要功能在编程中的作用:http://en.wikipedia.org/wiki/Main_function_ (programming)

Here is a little example for you:

这是一个小例子:

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


This may not be a popular solution for everyone, but I like the Application Framework in Visual Basic, even when using C#.

对于每个人来说,这可能不是一个流行的解决方案,但我喜欢Visual Basic中的应用程序框架,即使使用C#也是如此。

Add a reference to Microsoft.VisualBasic

添加对Microsoft.VisualBasic的引用

Create a class called WindowsFormsApplication

创建一个名为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);
    }

}

Modify your Main() routine to look like this

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

static class Program
{

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

        var application = new WindowsFormsApplication();
        application.Run(new Form1());
    }
}

This method offers some additional usefull features (like SplashScreen support and some usefull events)

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

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

#1


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

The arguments will then be stored in the args string array:

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

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

#2


The best way to work with args for your winforms app is to use

使用winforms应用程序的args的最佳方法是使用

string[] args = Environment.GetCommandLineArgs();

You can probably couple this with the use of an enum to solidify the use of the array througout your code base.

您可以将此与使用枚举相结合,以通过代码库巩固阵列的使用。

"And you can use this anywhere in your application, you aren’t just restricted to using it in the main() method like in a console application."

“你可以在应用程序的任何地方使用它,你不仅限于在main()方法中使用它,就像在控制台应用程序中一样。”

Found at:HERE

#3


You can grab the command line of any .Net application by accessing the Environment.CommandLine property. It will have the command line as a single string but parsing out the data you are looking for shouldn't be terribly difficult.

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

Having an empty Main method will not affect this property or the ability of another program to add a command line parameter.

具有空Main方法不会影响此属性或其他程序添加命令行参数的能力。

#4


Consider you need to develop a program through which you need to pass two arguments. First of all, you need to open Program.cs class and add arguments in the Main method as like below and pass these arguments to the constructor of the Windows form.

考虑您需要开发一个程序,您需要通过该程序传递两个参数。首先,您需要打开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])));           
   }
}

In windows form class, add a parameterized constructor which accepts the input values from Program class as like below.

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

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

To test this, you can open command prompt and go to the location where this exe is placed. Give the file name then parmeter1 parameter2. For example, see below

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

C:\MyApplication>Yourexename p10 5

From the C# code above, it will prompt a Messagebox with value p10 5.

从上面的C#代码,它将提示值为p10 5的Messagebox。

#5


You use this signature: (in c#) static void Main(string[] args)

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

This article may help to explain the role of the main function in programming as well: http://en.wikipedia.org/wiki/Main_function_(programming)

本文也可以帮助解释主要功能在编程中的作用:http://en.wikipedia.org/wiki/Main_function_ (programming)

Here is a little example for you:

这是一个小例子:

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


This may not be a popular solution for everyone, but I like the Application Framework in Visual Basic, even when using C#.

对于每个人来说,这可能不是一个流行的解决方案,但我喜欢Visual Basic中的应用程序框架,即使使用C#也是如此。

Add a reference to Microsoft.VisualBasic

添加对Microsoft.VisualBasic的引用

Create a class called WindowsFormsApplication

创建一个名为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);
    }

}

Modify your Main() routine to look like this

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

static class Program
{

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

        var application = new WindowsFormsApplication();
        application.Run(new Form1());
    }
}

This method offers some additional usefull features (like SplashScreen support and some usefull events)

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

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