WPF / Console Hybrid Application
Create a WPF app and add the following code to your App class:
public partial class App
{
protected override void OnStartup(StartupEventArgs e)
{
if (e.Args.Length > 0)
{
List<string> lowercaseArgs = e.Args.ToList().ConvertAll(x => x.ToLower());
if (AttachConsole(ATTACH_PARENT_PROCESS))
{
// your console app code
Console.Write("\rPress any key to continue...");
Console.ReadKey();
FreeConsole();
}
Shutdown();
}
else
{
base.OnStartup(e);
}
}
private const int ATTACH_PARENT_PROCESS = -1;
[DllImport("kernel32", SetLastError = true)]
private static extern bool AttachConsole(int dwProcessId);
[DllImport("kernel32.dll")]
private static extern bool FreeConsole();
}
You can conditionally start your WPF application by performing the following steps with the sample below.
- Add another entry point with the 'Main' method declarated with STAThreadAttribute. This is required by WPF.
Under your project's 'Build' properties, choose 'Console Application' as your output and your new 'Main' method as the application's 'Startup Object'.
using System; public static class Program { [STAThreadAttribute] public static void Main() { Console.WriteLine("What now?"); Console.ReadKey(true); App.Main(); } }
Your best bet would be to abstract out the code that actually does the work to a separate class library that has no UI and then create two applications one Console, the other WPF that call this.
A console application and an WPF application have entirely different application models so you can't reuse the same code in both applications.
Having a separate class library allows you do other things like use it in other applications such as a web site or client/server architecture.