views:

87

answers:

2

I want my project to be started through an class instead of a form, is there any way to do this? Or to be more precise is there any good way to make sure that the first class, except Program, that is started isn't a form-class.

I tried to change to my class in Program.main() but it looks like Application.run() needs a ApplicationContext.
I guess that I could change the Program-class to start another class and let that class start the form with Application.run() but I think that it will cause a lot of problem since I don't want the same form to be started first each time and Application.run() have to be used at least once and at most once. So I think it will be hard to keep track of if Application.run() has been used or not.

Another question that might be even more important; Is this a good way to do things in .net? The reason I want to do so is because I want to create some sort of MVC project where the class I want to start with is the controller and all forms I'll use will be views.

+1  A: 

To decide which class should run first, you should simply put in the Main method of your application in that class.

So basically, create a new class, put in the Main method (and remove it from Program.cs) do the logic you need and then launch the window as follows:

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

Form1 is the name of the form that has to be launched.

npinti
A: 

A sample implementation of a controller:

public class Controller : ApplicationContext {
    public Controller() {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        mInstance = this;
    }
    public Controller Instance { get { return mInstance; } }
    public void Start() {
        Application.Run(this);
    }
    public void Exit() {
        this.ExitThread();
    }
    public void CreateView(Form frm) {
        Views.Add(frm);
        frm.FormClosed += FormClosed;
        frm.Show();
    }
    private void FormClosed(object sender, FormClosedEventArgs e) {
        Views.Remove(sender as Form);
        // NOTE: terminate program when last view closed
        if (Views.Count == 0) Exit();
    }
    private List<Form> Views = new List<Form>();
    private Controller mInstance;

}

You could use it like this:

static class Program {
    [STAThread]
    static void Main() {
        var c = new Controller();
        c.CreateView(new Form1());
        c.Start();
    }
}

Also check out the WindowsFormsApplicationBase class as a good base class for your controller. Nice support for singleton apps and splash screens.

Hans Passant