简体   繁体   中英

Run a console application from a windows Form

I have a windows console app (that accepts parameters) and runs a process. I was wondering if there was any way to run this app from within a windows form button click event. I would like to pass an argument to it as well.

Thanks

只需使用System.Diagnostics.Process.Start和控制台应用程序的路径,并将参数作为第二个参数。

Assuming you have a form with a multiline textbox called txtOutput.....

private void RunCommandLine(string commandText)
    {
        try
        {
            Process proc = new Process();
            proc.StartInfo.CreateNoWindow = true;
            proc.StartInfo.UseShellExecute = false;
            proc.StartInfo.RedirectStandardOutput = true;
            proc.StartInfo.RedirectStandardError = true;
            proc.StartInfo.FileName = "cmd.exe";
            proc.StartInfo.Arguments = "/c " + commandText;
            txtOutput.Text += "C:\\> " + commandText + "\r\n";
            proc.Start();
            txtOutput.Text += proc.StandardOutput.ReadToEnd().Replace("\n", "\r\n");
            txtOutput.Text += proc.StandardError.ReadToEnd().Replace("\n", "\r\n");
            proc.WaitForExit();
            txtOutput.Refresh();
        }
        catch (Exception ex)
        {
            txtOutput.Text = ex.Message;
        }
    }

您将要使用System.Diagnostics.Process

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