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();

1 comment:

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!

InRiver: Not loading your extensions?

(You really need to in the loop to appreciate the issue this post addresses). Man, I've been fighting this problem for hours before I ...