I'm writing a program that requires the user to select a file when the program starts. If he cancel this the program exits.

Currently I'm creating an OpenFileDialog in the main form's constructor, but it's not working very well due to the following issues:

* If the user cancels I can't simply exit by closing the main form from the constructor. So I have to throw an exception that is handled in Main...ugly.

* If the user starts the program e.g. by double click on it in explorer the OpenFileDialog pops up. When the user has selected a file the main form is hidden behind the explorer window.

* I would like the main form to be visible and the OpenFileDialog on top of it instead of showing the main form after the OpenFileDialog has been closed.

I was looking for an event that would occur when the main form has been opened completely, but I can't find any.
Any advices...?

call the open file dialog box in the program's Main method. if its a success then call the application.run method passing the filename to the form's constructor. if its not a success then simple allow the main method to return closing the program.

using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace Serial
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            OpenFileDialog ofd = new OpenFileDialog();
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new Form1(ofd.FileName));
            }
        }
    }
}
commented: word for word what i would have post :p +1

Thanks, both of you. Form.Shown is just what i need.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.