Console application with Window (WPF and Windows Forms)

My latest project is a tool to help me analyze and visualize soccer data and for this I felt that I needed a Console Application to control and modify the data, and a window or two to show graphs and other visualizations. When I started I had a couple of options to make this work.

  1. Show a Console from wpf/windows forms project. This means that when i close my form, the app will terminate.
  2. Do a terminal with the rich text control.
  3. Show a wpf/windows form window from Console.

Since the application is controlled by the terminal and pops up a window every now and then option 1 goes away.
Option 2, well, I want a real feeling of a terminal, rich text doesn’t really give me that. So option 3 it was.

Console + Windows Forms

I turns out that for Windows Forms it was pretty straight forward.
I have created a Console Application project, added a “Windows Form” to my project that is called “WindowsForm”, and to show the Window form console, just do

One tip, since i was going to show graphs I needed to pass some data to my form and i did this with a custom constructor, and if you do this, don’t forget:

Otherwise it will be an empty control.

Console + WPF

Wpf was a little bit trickier, as always.

The first thing I did was to create a UserControl, and in the .cs file i changed the inheritance from UserControl to Window, and in the xaml i change the UserControl tag to Window.

The next step was to add a reference to System.Xaml. After this step it was possible to build at least.

In order to show the form I took a similar approach as for windows forms (but using a different package for application)

And this was the first lesson, apparently the Main must be marked as a STAThread (more info here)

This will indeed open a wpf window from a console, but as it turns out, Application.Run won’t return like the Windows Forms counterpart.

So my solution was to start another thread and use that to show the window, and the final code is shown below.

I pretty sure there will be tons of issues that i haven’t found yet, but so far so good 🙂

If you find problems or has a better solution, please leave a comment.

 

Leave a Reply

Your email address will not be published. Required fields are marked *