Wednesday, May 13, 2009

Where is the main method in my WPF application?

If you are an expert WPF developer and knows the answer just stop here.Rest will be boring for you.

Normally when a new deveoper comes into WPF from the .net 2.0 environment he will naturally look for the main method where the execution starts.He can't find out the main method by simply searching in the Visual Studio using ctrl+shift+f.So where is the main method ? or WPF application don't have anything like that ? then how the execution starts in wpf and where is the entry point?

The main method in WPF application lies in the file App.g.cs located at obj\debug.This is autogenerated and will not be visible until we press the 'Show all files' button in the solution explorer.See the screen shot below.

Adding our own Main method in WPF applications
Now it is clear that the WPF application has a mainmethod where the execcution starts.Let's check whether we can write our own main method.If we write a Main method in the App.Xaml.cs it will not compile by saying "App already define a member called 'Main' with the same parameter types".So what to do?

We can write in some other classes like Window1.xaml.cs.Then how the system identifies which Main should get called.That too simple.Go to project properties.Select application tab.Then change the start up object to Window1.cs.See the below code for more details


  1. thanks for the help

  2. Thanks, that was really useful.

  3. If you just want to initialize some additional components, an easier solution is just to add a constructor to Window1.xaml.cs (or whatever the class name might be).