9

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 :)

svick
  • 214,528
  • 47
  • 357
  • 477
dsp_099
  • 5,021
  • 13
  • 59
  • 115
  • 1
    What technology are you talking about? windows forms? asp.net web forms? asp.net mvc? wpf? – balexandre Jan 08 '12 at 11:23
  • @balexandre, good question. My guess/assumption is WPF, due to the tags used and the mentionned XAML errors and running it on different computers. – Lucero Jan 08 '12 at 11:25
  • 1
    @Lucero, the `wpf` tag was added by me, because of the talk about XAML errors and `MainWindow`. – svick Jan 08 '12 at 11:28
  • What do you call to close the application? Are you checking any of the UI elements in your code logic? What happens when you put the code after `InitialiseComponent()` call? And what is the error you are getting, you can read the InnerException by clicking View Error on your error popup. – Tomislav Markovski Jan 08 '12 at 11:31

2 Answers2

23

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?

svick
  • 214,528
  • 47
  • 357
  • 477
0

You have Window.Loaded event in WPF.

But if if you want to check for run permission before application loads ( due some resource consuption or some business strategy) use a bootstrapper a separate small executable that first launched by mainexe and after if everything ok a bootstrapper runs main exe

Tigran
  • 59,345
  • 8
  • 77
  • 117
  • `Window.Loaded` gets called even after the `Window`'s constructor, which the OP said is too late. – svick Jan 08 '12 at 11:28
  • @svick: don't see the point of "too late". OP says that he wants to run the check *as soon as* app starts. So there is, imo, a "normal" option is catching `Window.Loaded` or use a `bootstrapper`, which is more complicated to implement, but probably what OP wants actually. – Tigran Jan 08 '12 at 11:34