Can I change WPF application starting point ?

By Mirek on (tags: Starting Point, WPF, categories: architecture, code)

Is it possible to change starting point for WPF application, so that we can run some code before even the actual application is created? Keep reading to get know…

Usually when you want to run some preparation code in WPF application you just end up with overriding the OnStartup method of the application


public partial class App : Application
{
    protected override void OnStartup(StartupEventArgs e)
    {
        //do some preparation here
        //also access the command line arguments on e.Args
        base.OnStartup(e);
    }
}

But what if you want to run some code even before the App is created. Well it is quite easy and works in both .Net Framework and .NET 5 WPF applications.

All we need to do is to override the application starting object. Normally the compiler will create static Main method, attach it to the App class and make it an application starting point. This is default behavior.

To change it, in the first step we need to define our own starting point. So lets create a Program class and define a static void Main method in it (I like to stick to the naming and conventions used in all .Net applications)


public class Program
{
    [STAThread]
    static void Main(string[] args)
    {           
    }
}

Looks familiar right? One note here. As we are running WPF application we need to ensure the Single Threaded Apartment, for that the STAThread attribute here is used.

Next we need to tell the compiler to use this method as a starting point. To do that we have two opitions. One is to go to project settings and in Application tab set the Startup object to the Program class

2020-12-18 17_40_09-WPFCore5App - Microsoft Visual Studio

Second method is to edit project file and add following entry

<StartupObject>WPFCore5App.Program</StartupObject>

Now all we need is to create, initialize and start the application in Main method


public class Program
{
    [STAThread]
    static void Main(string[] args)
    {
App app = new App();
app.InitializeComponent();
app.Run();
}
}

That's it. Now we can run whatever we want before application start.

We can for example wrap it all in a Generic Host to have more control over how the application is maintained.