Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to have a WPF application print console output?

Tags:

c#

console

wpf

I have a simple WPF application. Under normal use, App.xaml will launch MainWindow.xaml. But I would like to set it up so that if it is invoked with a special command line argument, that it will function as a console application instead.

So here's roughly what my App.xaml.cs file looks like:

using System;

namespace MyProject
{
    public partial class App : Application
    {
        public void App_OnStartup(object sender, StartupEventArgs e)
        {
            if (e.Args.Length == 1 && e.Args[0].Equals("/console"))
            {
                Console.WriteLine("this is a test");
                Environment.Exit(0);
            }
            else
            {
                var mainWindow = new MainWindow();
                mainWindow.Show();
            }
        }
    }
}

I would expect that when I run MyProject.exe /console from the command line, it would print the string "this is a test". But right now it doesn't print anything. How can I get it to work?

like image 273
soapergem Avatar asked Aug 13 '15 03:08

soapergem


People also ask

Is WPF obsolete?

I think WPF will be dead in 2022 because its framework no longer supports new development, and Microsoft is pushing hard for a new cross-platform development framework, including the UNO platform and Xamarin. Electron is also more progressive compared to UWP.

How do I show console output in Visual Studio?

Press F11 . Visual Studio calls the Console.

Where is the console in WPF?

Right click on the project, "Properties", "Application" tab, change "Output Type" to "Console Application", and then it will also have a console.


1 Answers

We have special class for this purpose:

internal static class ConsoleAllocator
{
    [DllImport(@"kernel32.dll", SetLastError = true)]
    static extern bool AllocConsole();

    [DllImport(@"kernel32.dll")]
    static extern IntPtr GetConsoleWindow();

    [DllImport(@"user32.dll")]
    static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

    const int SwHide = 0;
    const int SwShow = 5;


    public static void ShowConsoleWindow()
    {
        var handle = GetConsoleWindow();

        if (handle == IntPtr.Zero)
        {
            AllocConsole();
        }
        else
        {
            ShowWindow(handle, SwShow);
        }
    }

    public static void HideConsoleWindow()
    {
        var handle = GetConsoleWindow();

        ShowWindow(handle, SwHide);
    }
}

Just call ConsoleAllocator.ShowConsoleWindow() and then write to Console

like image 194
Backs Avatar answered Nov 15 '22 21:11

Backs