13. December 2007 00:54
When you create a WPF application in Visual Studio the 'entry point' for the process, where the application is created and the first form displayed, is not directly apparent. Instead the start-up behaviour is controlled by setting attributes on the App.xaml, such as which form to start. At compile-time WPF generates the real entry point method using the classic static void Main() method signature in C#, or Public Shared Sub Main() in VB.NET. Inside the Main() method WPF creates an instance of one of your classes which derive from System.Windows.Application, and calls the blocking Run() method on this Application-derived class which keeps the process "alive". Generally this is a useful abstraction, hiding away some of the lower-level details of how the WPF application starts up, however sometimes you want to provide your own version of the Main() method. So how do you tell WPF to use your main method and not its own?
The way WPF knows to create the Main() method for a particular xaml file is through the build action property set for App.xaml - it has a build action of ApplicationDefinition. By changing this to Page WPF won't create the Main method and you can provide your own in a regular class file you add to the project.
It is important to note that when you provide your own Main() method that the method should be adorned with the STAThread attribute, which sets the threading model for the process. You can either look at the current generated Main() method for your project as a starting point (it should be in the obj folder) or use the following code:
static void Main()
YourApplicationName app = new YourApplicationName();