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

128

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

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

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

  static void main()
  {
  }
6个回答

233

与您的WinForms应用程序一起使用参数的最佳方法是使用

string[] args = Environment.GetCommandLineArgs();

你可能可以将这个方法与使用枚举相结合,以巩固在整个代码库中对数组的使用。

“而且你可以在应用程序的任何位置使用它,不仅仅像在控制台应用程序的main()方法中使用它。”

来源:这里


27
数组的第一个元素包含正在执行的程序的文件名。如果文件名不可用,则第一个元素等于String.Empty。其余元素包含在命令行上输入的任何其他标记。 - EKanadily
@docesam 非常感谢,这对我帮助很大!一直在想为什么它会试图将程序本身作为文本加载。 - Kaitlyn
多年的C#开发经验,我从未知道这个方法的存在。不错。 - CathalMF
1
使用这种方法与发送参数 main(string[] args)相比,是否有任何好处? - Adjit
Environment.GetCommandLineArgs(); 是一个有用的方法,如果您不想在程序中传递参数或保存它们,可以稍后获取这些参数。使用 'Main(string[] args){' 的方式仍然有效并且可行。 - Delta

133
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

6
输入:"whatever.exe -v foo /lol nisp"。输出:args[0] = "-v"; args[1] = "foo"; args[2] = "/lol"; args[3] = "nisp"。这还有什么比这更容易的呢? - Callum Rogers
真不敢相信我在整整一年中看到了那么多次的 'string[] args',直到现在才意识到它是什么!哈哈 - Niklas
2
看起来 args[0] 是应用程序的完整路径和可执行文件名称,而 args[1] 则是第一个参数。 - Allan F
这个问题涉及到WinForms应用程序--它们没有Console,用户功能需要从主窗体运行。 - ivan_pozdeev
@ivan_pozdeev Console 只是代码中的示例,如代码中所注释的那样。 - Thomas

17

假设您需要开发一个程序,需要传递两个参数。首先,您需要打开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 Form类中,添加一个带参数的构造函数,该构造函数可以从 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的Messagebox。


12

通过访问Environment.CommandLine属性,您可以获取任何.Net应用程序的命令行。它将作为一个单一字符串呈现,但解析出所需数据不应该太困难。

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


26
或者使用Environment.GetCommandLineArgs(),它返回一个字符串数组,就像Main(string[] args)一样。 - Brettski

7
您使用的是这个签名:(在C#中)静态void Main(string [] args)
本文可能有助于解释编程中主要函数的作用: 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");
    }
}

4

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

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

该方法提供了一些额外的有用功能(例如启动屏支持和一些实用的事件)。
public event NetworkAvailableEventHandler NetworkAvailabilityChanged;d.
public event ShutdownEventHandler Shutdown;
public event StartupEventHandler Startup;
public event StartupNextInstanceEventHandler StartupNextInstance;
public event UnhandledExceptionEventHandler UnhandledException;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接