简体   繁体   中英

How to create a C# application that opens “cmd.exe” in another window?

What I'd like to Do

I'd like to create a simple C# application that creates a Process object (the application's child process) that runs cmd.exe and, inside that shell, execute the command echo "Hello World!" (or whatever arbitrary string I specified before compiling the application). The C# application, when built and ran, creates and leave the shell in this state:

所需的窗口

Attempts

I've searched stackoverflow and MSDN for examples but it's difficult to find the right options to set for Process , ProcessStartInfo . In particular, I tried:

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            /*
            System.Diagnostics.Process process = new System.Diagnostics.Process();
            System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
            startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
            startInfo.FileName = "cmd.exe";
            startInfo.Arguments = "echo helloworld!";
            string strCmdText;
            process.StartInfo = startInfo;
            process.Start();
            */


            var proc = new Process
            {
                StartInfo = new ProcessStartInfo
                {
                    FileName = @"cmd.exe", // iexplorer.exe opened up ie!
                    Arguments = "",
                    UseShellExecute = false,
                    RedirectStandardOutput = true,
                    CreateNoWindow = false,
                    WorkingDirectory = @"C:\Users\mtran\Desktop\ConsoleApp1", 
                    WindowStyle = ProcessWindowStyle.Normal

                }
            };
            proc.Start();
        }
    }
}

but either second cmd window (for the child process) never appears (if I set RedirectStandardOutput = false )or the output of from the child process gets written to the parent's cmd window.

Try this:

Process.Start("cmd.exe", "/k ECHO hello Juan!");

It will launch the command window, execute the ECHO statement and keep the window open.

Feel free to use a ProcessStartInfo instance as the parameter if you need additional configuration.

If you run cmd /? on a command prompt, you can see additional information about the switches:

/C Carries out the command specified by string and then terminates

/K Carries out the command specified by string but remains

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM