Run a console application from a windows Form

2019-02-18 11:07发布

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

3条回答
对你真心纯属浪费
2楼-- · 2019-02-18 11:48

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;
        }
    }
查看更多
欢心
3楼-- · 2019-02-18 12:06

Just use System.Diagnostics.Process.Start with the path to the console application, and the parameters as the second argument.

查看更多
做自己的国王
4楼-- · 2019-02-18 12:09

You'll want to use System.Diagnostics.Process

查看更多
登录 后发表回答