9

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?

Community
  • 1
  • 1
Matthew Scharley
  • 127,823
  • 52
  • 194
  • 222
  • Sorry, haven't you referenced your answer? May be I do not understand what you want to do instead. – Markus Mar 25 '11 at 09:14
  • @Markus that answer is specifically and only applicable to WinForms. WPF has a different startup mechanism, so that answer isn't applicable here (there is no `Program.cs` for instance) – Matthew Scharley Mar 25 '11 at 09:15
  • @Markus: There is no access to the `Main` method in a normal WPF application. – Daniel Hilgarth Mar 25 '11 at 09:16

2 Answers2

14

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.

Eamon Nerbonne
  • 47,023
  • 20
  • 101
  • 166
10

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.

Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
  • 2
    It's worth noting that in an application that you're doing something like this in, you probably want to set `ShutdownMode = ShutdownMode.OnExplicitShutdown;` as Eamon mentions in his answer. – Matthew Scharley Mar 25 '11 at 10:17