Passing command line arguments to a Form (C#)

It looks like some people who are finding my entry How To Create a Console/Window Hybrid Application in C# really just want to pass command line arguments to a windows form.

Here's an example.
Since I wrote this example up "by hand" on my Ubuntu machine, I put the Main entry point and Form1 class in the same file for the sake of demonstration. Visual Studio would split them up, but the code is essentially the same.
The idea is very simple and makes perfect when you think of your Form from an OOP perspective: pass the argument(s) to the Form's constructor.

That's it!
Console GUI command line args

//gmcs /r:System.Windows.Forms.dll /r:System.Drawing.dll Program.cs
//mono Program.cs
using System;
using System.Drawing;
using System.Windows.Forms; //System.Windows.Forms.dll

class Program{

	[STAThread]
	public static void Main(string[] args){

		if(args.Length == 0) return;
		string name = args[0];

		Application.EnableVisualStyles();
		Application.Run(new Form1(name));
	}
}

class Form1 : Form{
	private Button button;

	public Form1(string name){ 

		this.Height = 200;
		this.Width = 700;
		
		Label label = new Label();
		label.Text = "command line: " + name;
		label.Font = new System.Drawing.Font("Veranda", 18); 
		label.Height = this.Height;
		label.Width = this.Width;
		
		this.button = new Button();
		this.button.Text = "Ok";
		this.button.Width = this.Width / 2;
		this.button.Height = 50;
		this.button.Location = new Point(1,50);
		this.button.Click += new EventHandler(this.button_click);

		this.Controls.Add(this.button);
		this.Controls.Add(label);
	}

	private void button_click(object sender, EventArgs args){
		this.Close();	
	}
}
| Comments (0)TrackBacks (0)

0 TrackBacks

Listed below are links to blogs that reference this entry: Passing command line arguments to a Form (C#).

TrackBack URL for this entry: http://www.rootsilver.com/mt-tb.cgi/97

Leave a comment