user3292642 user3292642 - 8 months ago 44
C# Question

Show Wpf Window from Console App

I'm simple trying to show a WPF Window from a Console App. In my solution I got a console application which is the startup project and creates a Wpf Window like this:

class Program
{
[STAThread]
static void Main(string[] args)
{
var thread = new Thread(Foo);
thread.Start();

Console.ReadKey();
}

private static void Foo()
{
var markerService = new MarkerService();
var viewModel = new MainViewModel();
markerService.Register(viewModel);
var mainView = new MainWindow { DataContext = viewModel };
mainView.Show();
}
}


MainWindow
and
MainViewModel
are just empty. When I start the project The Wpf Window is shown but doesn't respond (cursor is busy).

Any help is appreciated.

regards

Answer Source

You need to use Dispatcher.Run to start a message loop.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using WpfApplication1;
using System.Windows.Threading;

namespace ConsoleApplication2
{
    class Program
    {
        [STAThread]
        static void Main(string[] args)
        {
            var thread = new Thread(Foo);
            thread.ApartmentState = ApartmentState.STA;
            thread.Start();

            Console.ReadKey();
        }

        private static void Foo()
        {
            var markerService = new MarkerService();
            var viewModel = new MainViewModel();
            markerService.Register(viewModel);
            var mainView = new MainWindow { DataContext = viewModel };
            mainView.Show();

            Dispatcher.Run();
        }
    }
}

or you can use the "Application" object style suggested by @mm8, or a 3rd alternative is to just do:

        mainView.ShowDialog(); // internal message pump used

More here: