views:

963

answers:

6

C#: I want to pass messages like a file path to my forms application like a console application, how would I do that?

I was told I needed to find my main method to add string[] args, but I wouldn't know which one that would be in Windows Forms. Which would my main method be in C# windows forms application?

+1  A: 

If you want to get access to the command line parameters, use Environment.CommandLine

string args = Environment.CommandLine;

You can do this whether or not you have a main method with string[] args in your code.

JaredPar
+1  A: 

There's one Main(), which is inside Program.cs. But in WinForms app Environment.GetCommandLineArgs() will be a better option.

Anton Gogolev
+2  A: 

in your public constructor, use the following:

string[] args = Environment.GetCommandLineArgs();

this will give you a string array of the arguments.

Brett McCann
+6  A: 

Ok, string[] args = Environment.GetCommandLineArgs() is a better option. But I will keep the following answer as an alternative to it.

Look for a file called Program.cs containing the following code fragment...

static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }
}

and change that to

static class Program
{

    public static string[] CommandLineArgs { get; private set;}

    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main(string[] args)
    {
        CommandLineArgs = args;
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }
}

Then access the command line args from your form ...

Program.CommandLineArgs
SDX2000
+3  A: 

Your Main() method is located in Program.cs file, typically like this:

[STAThread]
static void Main()
{
  Application.EnableVisualStyles();
  Application.SetCompatibleTextRenderingDefault(false);
  Application.Run(new Form1());
}

You should modify the Main() to the following:

static void Main(string[] args)

You'll have access to the arguments passed.

Also, you could access the arguments using Environment.GetCommandLineArgs()

hmemcpy
A: 

hey guise when i do so with my application i get the following string "D:\MyData~1\MyMain~1.pfb" and it supposed to be like that "D:\My Data\My Main Phone Book.pbf" and i don't know why pls any bodyhas asolution to this

falcon eyes
Hi falcon eyes, you need to ask this as a separate question - i.e. as its own question. be sure to give an example of the code you're running and the output you're getting.
Matt Ellen