23 August, 2010

WPF: Where is the Main method? Or how to overwrite the Main method?

If you want to be able to control in details the startup of your WPF application, you will be needing access to the Main method. This can be the case if you want to make sure that only a single instance is running on the entire PC (by using Mutexes). But, where on Earth is the Main method to control the application startup?

Well – Microsoft has been so “kind” as to hide this method from us! It is located in obj/debug in app.g.cs (‘g’ short for generated). As it is generated, it makes little sense to edit this file as it will be overwritten on next build. So what to do? Here is how:

1) Select your project’s current startup file (app.xaml)
2) Set BuildAction = Page
3) Add a file as below (MyApplication.cs)
Note: Do not call this file Application.cs and the class Application. It will conflict with the inner workings of WPF

You now have complete control of the Main method and the application startup.

public class MyApplication
public static void Main(string[] args)
App app = new App();


walter said...

As I'm new to WPF, I had to think a bit, but wrapping the code in a namespace & adding "using System;" had this running beautifully. Thanks!


Thanks for a wonderful share. Your article has proved your hard work and experience you have got in this field. Brilliant .i love it reading. Download TutuApp

CNG said...

Your blog provided us with valuable information to work with. Each & every tips of your post are awesome. Thanks a lot for sharing. Keep blogging, Cydia Download iOS 11.3

iPhone/XCode - not all cases are equal!

This bit me! Having made some changes to an iPhone application (Obj-C); everything worked fine in the simulator. But, when deploying the s...