1

I created an empty project in Visual Studio and added the required assembly references, a class with a static Main function and a WPF Window.

I then create an instance of the Window and show it, but after execution everything closes as there is nothing keeping the thread open/running.

Adding a while(true) loop keeps it open but freezes the primary thread.

Adding the while(true) loop to a new thread keeps that thread open but the primary thread still finishes execution closing everything else.

How would I keep the application open?

John Saunders
  • 160,644
  • 26
  • 247
  • 397
Stuyvenstein
  • 2,340
  • 1
  • 27
  • 33

2 Answers2

5

The easy answer is to just use the stock WPF application project instead of rolling your own, as its generated code handles this for you.

The longer answer is to utilize Application.Run explicitly. You can see what the framework does in this answer: https://stackoverflow.com/a/2694710/1783619

This keeps a long-running thread so that your application will not terminate early, as you have seen.

Community
  • 1
  • 1
BradleyDotNET
  • 60,462
  • 10
  • 96
  • 117
  • I saw the Application.Run in a forms application but the function only accepts windows forms and I want to try it with a WPF Window. – Stuyvenstein Sep 30 '14 at 18:20
  • @Anomaly The WPF version will work off of an WPF `Application` object (see the standard App.xaml.cs). Its the same function call, as shown in the linked SO post. – BradleyDotNET Sep 30 '14 at 18:22
1

Create a new WPF application / project:

In Visual Studio do: File -> New -> Project -> Visual C# -> WPF application

samwise
  • 1,907
  • 1
  • 21
  • 24
  • I am trying to create Windowed apps from an empty project, I know that I can create WPF or Forms apps by selecting the appropriate project. – Stuyvenstein Sep 30 '14 at 18:22
  • ... or at least do this so you can see what the auto-generated code does – Robert Levy Sep 30 '14 at 18:22
  • With WPF I don't see any auto-generated code, only with WinForms but it uses `Application.Run(new Form())` which only accepts forms – Stuyvenstein Sep 30 '14 at 18:25
  • @Anomaly In this case, the auto-generated code isn't generated until build time, so is harder to find. Its still there, and still does the same thing though :) – BradleyDotNET Sep 30 '14 at 18:27
  • Here I've got you the code from the auto generated main method of a WPF application: `public static void Main() { MyApp.UI.App app = new MyApp.UI.App(); app.InitializeComponent(); app.Run(); }` You can find the auto generated code in your projects folder -> obj -> Debug – samwise Sep 30 '14 at 18:44