Embed a Console Window inside a WPF Window Embed a Console Window inside a WPF Window wpf wpf

Embed a Console Window inside a WPF Window


In addition to Reed Copsey's excellent advice on embedding a console window in a WPF application, an alternative strategy which is ridiculously easy to implement would be to simply issue the command via the Process class and redirect the two streams into native WPF TextBlocks. Here's a screenshot...

enter image description here

This WPF app (wired to the Windows Explorer context menu for 'exe' files) executes the program and pipes the results into the appropriate window.

It's designed to help when you want to run a console utility and when you click it, the utility goes whizzing by in a console window and you never get to see what happened. It is also wired to 'csproj' files to run MSBuild on them from Explorer.

The point being that sometimes it's easier and more scalable to do it yourself rather than try to host a console window...

The internals of this app use this class...

public class ProcessPiper{    public string StdOut { get; private set; }    public string StdErr { get; private set; }    public string ExMessage { get; set; }    public void Start(FileInfo exe, string args, Action<ProcessPiper>onComplete)    {        ProcessStartInfo psi = new ProcessStartInfo(exe.FullName, args);        psi.RedirectStandardError = true;        psi.RedirectStandardOutput = true;        psi.UseShellExecute = false;        psi.WorkingDirectory = Path.GetDirectoryName(exe.FullName);        Task.Factory.StartNew(() =>            {                try                {                    ExMessage = string.Empty;                    Process process = new Process();                    process.StartInfo = psi;                    process.Start();                    process.WaitForExit();                    StdOut = process.StandardOutput.ReadToEnd();                    StdErr = process.StandardError.ReadToEnd();                    onComplete(this);                }                catch (Exception ex)                {                    ExMessage = ex.Message;                }            });    }}

This class executes the named 'exe' file and captures the output and then calls the View Model. The whole coding drill should take about an hour or so...

Docs on the Process class are here: http://msdn.microsoft.com/en-us/library/system.diagnostics.process.aspx


You should be able to use the same technique as the Windows Forms application you showed by reparenting into an HwndHost. You could even just adapt the Windows Forms code, and put this directly into WindowsFormsHost control.