Matthew Scharley
Matthew Scharley

Reputation: 132284

What code controls the startup of a WPF application?

More specifically, how could I setup a startup sequence like this one in WPF where no window is shown at start, but a notification icon is present?

Upvotes: 9

Views: 9501

Answers (2)

Eamon Nerbonne
Eamon Nerbonne

Reputation: 48066

To run, WPF requires an Application object. when you execute Run on that object, the application goes into an infinite loop: the event loop responsible for handling user input and any other OS signals.

In other words, you can include a custom Main function in a WPF app just fine; it merely needs to look something like this:

[STAThread]
public static void Main(string[] args) {
    //include custom startup code here

    var app = new MyApplication();//Application or a subclass thereof
    var win = new MyWindow();//Window or a subclass thereof
    app.Run(win); //do WPF init and start windows message pump.
}

Here's an article about some of the gotcha's using this approach: The Wpf Application class: Overview and Gotcha. In particular, you'll probably want to set things like Application.ShutdownMode. This approach leaves you free to do whatever you want before any WPF code runs - but, more importantly, I hope it elucidates how WPF apps start.

Upvotes: 14

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174329

Remove the StartupUri attribute from the Application root tag of your App.xaml file and add the code you want to execute in the Application.Startup event handler.

Upvotes: 10

Related Questions