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?
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.
Press F11 . Visual Studio calls the Console.
Right click on the project, "Properties", "Application" tab, change "Output Type" to "Console Application", and then it will also have a console.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With