Question

Always annoyed me how C# wants to do the startup for you. So now I am trying to make my own main method. It's not working:

I have provided this main method:

[System.STAThreadAttribute()]
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static void Main()
{
    Model model= new Model();
    Controller controller = new Controller(model);
    MainWindow window = new MainWindow(controller, model);
}

This method is run, but I cant see anything visual. I think I miss something from the following normal main code:

Application.App app = new Application.App();
app.InitializeComponent();
app.Run();

I have tried overriding OnStartUp witht the same code, but that throws an exception. If you have other solutions I am willing to hear. I just can't see why my MainWindow has to be created first.

Was it helpful?

Solution

You're right: you need to instantiate an Application and call Run on it. (You'd do this in Main.) To make it show your window when it runs, there are three options:

  • Use the Run(Window) overload, e.g. MainWindow w = ...; new MyApp().Run(w);
  • Set the StartupUri e.g. myApp.StartupUri = new Uri(...); myApp.Run();
  • Do the Show in the Startup event or OnStartup override e.g. myApp.Startup += (...) => new MainWindow().Show();

Examples of manual startup code are shown in MSDN under the Application.Run() and Application.Run(Window) entries - these should get you started! The Run() overload also discusses why Application.Run is needed and what it does e.g. starting the dispatcher loop.

OTHER TIPS

Always annoyed me how C# wants to do the startup for you. So now I am trying to make my own main method. It's not working:

C# doesn't do the startup for you. It inserts code that does it for you. You could always change the code and so whatever you wanted. First thing I would do if I were you - Right click the project file and select Properties. Under Application (the top tab) - see Startup Object.

You can select the form

Also - You're missing a line if you want the window to appear:

window.Show();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top