0

How does one properly start C# app with different Form when using "Open with..." on file.

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

    if (args.Length == 1)
    {
        if (System.IO.File.Exists(args[0]))
            Application.Run(new DetailsForm(args[0]));
    }
    else Application.Run(new MainForm());
}

The above code works well when you drag and drop file on MyApplication.exe (only DetailsForm starts), but it does not work when using File > Open with > MyApplication.exe. For some reason it loads MainForm as if ignoring Main().

How are the parameters passed when using "Open With"?

EDIT

Logging in main() returns no parameters when using "Open With" option from Windows file context menu. However, the "else" block is also NOT executed. What starts the MainForm then?

The MessageBox from code below does NOT open when using "open with" on file (i.e. opening JPG with my program). It's as if it was ignoring the entire if-else clause and starting MainForm from somewhere else.

else 
{
    MessageBox.Show("No parameters"); 
    Application.Run(new MainForm());
}

EDIT / Solution

Happened to be Windows-related problem. Leaving the question here in case someone happens to have the same issue.

3
  • 1
    Check how many parameters you have in that case. BTW why args.GetLength(0) instead of args.Length? May 21, 2014 at 16:28
  • Why don't you use logging to see the arguments!? May 21, 2014 at 17:13
  • @VahidND I did. No parameters when using "Open with".
    – yosh
    May 22, 2014 at 8:54

3 Answers 3

1

try out bellow, I faced the same issue some time before.

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

1
  • Opening Forms work fine, I wrote it in question. Nevermind anyway, was Windows bug.
    – yosh
    May 22, 2014 at 10:09
0

Try using the following if statement:

if (args.Length >= 1)
{
    if (System.IO.File.Exists(args[0]))
        Application.Run(new DetailsForm(args[0]));
}
else 
{
    Application.Run(new MainForm());
}

I was able to test this with copying a file over as well as using open with.

1
  • This is pretty much the same code I have. Problem is that when using "open with" there is no args.
    – yosh
    May 22, 2014 at 9:09
0

Found solution. Which was Windows-related... I had the same application in 2 directories (old and new). Apparently, even when using "Browse" to new location, then the "Open with" dialog starts the application from old path.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.