How to run code right when a C# application starts?

dsp_099 picture dsp_099 · Jan 8, 2012 · Viewed 19.2k times · Source

I have put some code inside of the public MainWindow() {} but I kept getting some obscure XAML parsing errors as soon as I did that (not on my computer but on 3 others I've tried it on - yep!)

Is there the preferred way to run code AS SOON as t he application starts?

The theory is I want it to call home and ask it it's ok to start. If it's not, I want the app to close out. Call it a makeshift copy-protection :)

Answer

svick picture svick · Jan 8, 2012

Under normal circumstances, WPF creates the Main method (the entrypoint of the application) for you. Your options

  • Create a handler for the Application.Startup event and put your code there. Alternatively, you can override the OnStartup() method.
  • If that's too late for you, put your code in the App's parameterless constructor (it probably doesn't exist, but you can create it).
  • If even that's too late, you can create your own Main() method. There are several ways how to do that. Probably the easiest is to put it in another class and tell Visual Studio you want to use this method in the project's properties.

On the other hand, you said you're getting some obscure XAML parsing errors. Maybe you should figure out what exactly do they mean?