1

In my WPF application I am trying to open cmd.exe through System.Diagnostics.Process but every time it hits process.Start() it closes immediately and I cannot write anything else to it. However if I call the static Process.Start() it will stay open but then I am unsure how to write to it. See below.

        var processInfo = new ProcessStartInfo("cmd.exe")
        {
            UseShellExecute = false,
            RedirectStandardInput = true,
        };

        var process = new Process()
        {
           StartInfo = processInfo,
        };

        process.Start(); // This close immediately and not work 

        Process.Start("cmd.exe"); // This will work but can't write to it

        process.StandardInput.WriteLine(someText);
        process.StandardInput.WriteLine(moreText);

2 Answers2

1

Use to wait for cmd.

process.WaitForExit(); 
Shivani Katukota
  • 859
  • 9
  • 16
0

I did some research and found the solution implemented Here works. Not sure if this is the best approach, but it worked for me.

[DllImport("kernel32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool AllocConsole();

private void BtnSubmit_OnClick(object sender, RoutedEventArgs e)
    {
        var processInfo = new ProcessStartInfo("cmd.exe")
        {
            UseShellExecute = false,
            RedirectStandardInput = true
        };

        var process = new Process()
        {
            StartInfo = processInfo,
        };

        AllocConsole();
        process.Start(); // This close immediately and not work 

        process.StandardInput.WriteLine("someText");
        process.StandardInput.WriteLine("moreText");
        process.WaitForExit();
    }

enter image description here

Kishore
  • 653
  • 6
  • 16
  • So this works well on my Windows 7 laptop but in Windows 10 it does stay up but the directories are blank and whatever I write to it does not show up. – Steve Goldman May 18 '18 at 16:31
  • Btw - I don't know if this was obvious or not but I did not know. This is only an issue when debugging in Visual Studio. Once you deploy your project and it runs on the .exe file the command prompt window stays up and you can write to it no problem! – Steve Goldman May 18 '18 at 18:43