Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Start WPF Application in Console Application

Tags:

c#

wpf

Is it possible to start WPF Application in Console mode?

public partial class App : Application
{
    public App()
    {
        InitializeComponent();
    }
}

<Application x:Class="WPF.App"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
</Application>

[STAThread]
static void Main(string[] args)
{
  if (args.Length > 0)
  {
     switch (args[0].ToLower())
     {
       case "/g": RunApplication(); break;
     }
  }
}

private static void RunApplication()
{
    var application = new System.Windows.Application();

    application.Run(new App());
}

It will show Argument type 'WPF.app' is not assignable to parameter type 'System.Windows.Window'.

Any solution to work around it?? Any different between

1.public partial class App : Application

2.public partial class App : Window

like image 270
king jia Avatar asked Nov 19 '15 02:11

king jia


People also ask

Can WPF application run in browser?

WPF Browser applications (or XAML Browser applications, or XBAP) are a specific kind of application that are compiled into . xbap extensions and can be run in Internet Explorer.


1 Answers

You could declare a Window and then start your app this way:

var application = new System.Windows.Application();
application.Run(new Window());

EDIT:

You seem a bit confused, so let me explain:

Say you have a program:

using System;

namespace ConsoleApplication
{
    class Program
    {
        [STAThread]
        static void Main(string[] args)
        {
            RunApplication();
        }

        private static void RunApplication()
        {
            var application = new System.Windows.Application();
            application.Run();
        }
    }
}

This will run a WPF application with no Window.

If, on the other hand, you pass a Window into application.Run(), you will get a WPF window. App should not derive from Window, since it should derive from Application.

Application.Run method either takes no arguments or a Window. It does not take Application. Therefore, if you want to start a previously created Application, as you have over there, you should do something like this:

private static void RunApplication()
{
    var application = new App();
    application.Run();  // add Window if you want a window.
}

Lastly, if you want to just use application.Run() and not have to pass a specific Window, just declare a starting Window in your Application XAML using StartupUri:

<Application x:Class="WPF.App"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         StartupUri="SomeWindow.xaml">
</Application>
like image 143
B.K. Avatar answered Sep 28 '22 06:09

B.K.