How to Pass Command-Line Arguments to a Winforms Application

How do I pass command-line arguments to a WinForms application?

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:

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

Command line arguments using in Windows form

Something like this:

var cmdArgs = Environment.GetCommandLineArgs();

if (cmdArgs.Length < 2)
{
MessageBox.Show("No JSON file specified!");
}

var jsonFilename = cmdArgs[1];

If you do more complex command line parameter parsing I suggest to use an existing library like this one.

Update:

Here is where you can attach your event-handler (or create a new one doing a double-click):

Sample Image

Windows form application command line arguments

This is an example of the startup code I use in a project that runs as a form app or as a formless app depending on command line arguments.

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

Note this only works because nothing in my alternative entry point depends on events, etc. that are provided by the runtime environment Application.Run() method which includes handling windows messages, etc.

How do I handle Command Line Arguments in Winforms if I don't want to load Main form?

I found a neat and simple to implement solution using the example in my question provided by microsoft.

I created this application context class that is responsible for everything in the application and I use this instead of a form in the Application.Run() as shown below.
To achieve the behavior in the question, I am using a second form that is hidden and only the taskbar icon is shown. If the user wants to see how the process is doing, they can click the taskbar icon and see the logging window, which is actually the ConfigurationApplierForm in the example bellow.

class AnApplicationContext: ApplicationContext
{
private Form _currentForm;

Note the constructor is private, the main is inside this class and declared static.

private AnApplicationContext()
{
Application.ApplicationExit += new EventHandler(this.OnApplicationExit);

// choose which form to show based on arguments
if(Environment.GetCommandLineArgs().Contains("-apply"))
{
_currentForm = new ConfigurationApplierForm();
}
else
{
_currentForm = new ConfigurationActionManagerForm();
}

// initialize the form and attach event handlers
_currentForm.FormClosed += new FormClosedEventHandler(this.OnCurrentFormClosed);
_currentForm.ShowDialog();
}

Main is here, a little bit different from the original. Notice the argument in the Run method

[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
// context is passed instead of a form
Application.Run(new AnApplicationContext());
}

private void OnCurrentFormClosed(object sender, EventArgs e)
{
ExitThread();
}

private void OnApplicationExit(object sender, EventArgs e)
{
/* is there anything to do when all forms are closed
and the application is going to die?*/
}
}

Also, we need to tell the project that this is the startup project.

Project Properties -> Application -> Startup Project

Passing command line arguments to a windows form file in C++/CLI

Can you not create an overloaded constructor for the form. i.e.

public ref class Form1 : public System::Windows::Forms::Form
{
public:
Form1(String^ argument)
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
// Use "argument" parameter as req'd.
}

Form1(void)
{
//....usual constructor here...
//..etc...

then from main

// Create the main window and run it
Application::Run(gcnew Form1(argument));

Application.Run(new Form1()); via Command Line Arguments

You can change your 'Main' method in 'Program.cs' to this:

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

if (args.Contains("-form2"))
Application.Run(new Form2());
else
Application.Run(new Form1());
}

Passing argument to windows application

If you mean command line argument, I don't think there's much you can do unless you add a property to your class. But you can always access the args through this function Environment.GetCommandLineArgs().

Can anyone help me about command line parameters in a WinForms application?

It's actually quite simple to do.

When your application loads, get a list of the command line variables, then iterate through them and look for the one you want, then act accordingly:

Public Sub Main()
Dim arguments As String() = Environment.GetCommandLineArgs()

For Each a In arguments 'loop through the args in case there are multiple
Select Case a.ToUpper 'compare in uppercase if you don't care how the user enters it.
Case "-U"
'the -U argument was found, set a flag, or perform an action, or otherwise act accordingly.
End Select
Next
End Sub

I always put it in a select case, because in my apps, I may have multiple arguments and I loop through them all and set properties accordingly. In a select case, it's easy to add other parameters later. You can easily add a case else in the event you want to throw up an 'invalid argument' message.



Related Topics



Leave a reply



Submit