Creating a custom Main method in a WPF application

 
 
  • Gérald Barré

WPF generates a default Main method for you. This method starts the WPF application. In my case, I wanted to ensure only one instance of the application is running. You can make the check in the Startup event, but this means that your code will be executed once all WPF DLLs are loaded and some of the WPF startup code is executed. This can take a few hundred milliseconds, not a lot, but for a good UX this can be too much. So, I wanted to create a custom Main method.

The Main method is generated for the item with Build Action equal to Application Definition. By default App.xaml has this build action as you can see in the properties window:

You can change the build action to Page to prevent the generation of the Main method:

csproj (MSBuild project file)
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>WinExe</OutputType>
    <TargetFramework>net7.0-windows</TargetFramework>
    <Nullable>enable</Nullable>
    <UseWPF>true</UseWPF>
  </PropertyGroup>

  <ItemGroup>
    <ApplicationDefinition Remove="App.xaml"/>
    <Page Include="App.xaml"/>
  </ItemGroup>
</Project>

Then, you can implement your Main method:

C#
[STAThread]
static void Main()
{
    // TODO Whatever you want to do before starting
    // the WPF application and loading all WPF dlls
    RunApp();
}

// Ensure the method is not inlined, so you don't
// need to load any WPF dll in the Main method
[MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
static void RunApp()
{
    var app = new App();
    app.InitializeComponent();
    app.Run();
}

Do you have a question or a suggestion about this post? Contact me!

Follow me:
Enjoy this blog?Buy Me A Coffee💖 Sponsor on GitHub