How do I get arguments in a form application?

23,090

Solution 1

Environment.GetCommandLineArgs

Solution 2

Open up program.cs, on a file > new > winform project, you'll get

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

change this to

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

Now its just like the console apps, you'd access them via args.

Even if you don't go with this option, you should be aware of how the win form app is initialized :) This way, you could run different forms or not run a form at all.

Share:
23,090
Moon
Author by

Moon

Updated on July 09, 2022

Comments

  • Moon
    Moon almost 2 years

    I can find many examples on how to get arguments in a console application, but I can't seem to find an example of how to get arguments in a windows form application.

    I would like to following things.

    1. whenever I open a jpg file, windows launches my application.
    2. I would like to know path and name of the jpg file from my application.

    How do i do that?

  • Allen Rice
    Allen Rice almost 15 years
    A little cleaner than my method and I can't find anything negative about it. You may want to go with this for simplicity sake
  • Thorarin
    Thorarin almost 15 years
    Hmm, I don't agree on this being cleaner than using a method parameter. The latter gives you a fixed point where to decide how your application should behave at startup, rather than parsing the command line in some arbitrary spot.
  • Nathan McKaskle
    Nathan McKaskle over 10 years
    I tried using this example from Microsoft, however, I got nothing when the application opened. There were no arguments. That said, I didn't open it from a command line, I opened it from Explorer, by double clicking the file.
  • Ashwani
    Ashwani over 10 years
    That's by design. Opening a program from Windows Explorer does not send any command line arguments.