此代码演示了如何执行命令行进程并在Windows表单文本框中显示其实时输出。 让我们完善它,以清晰和鲁棒。
>
改进的代码:
<code class="language-csharp">using System; using System.Diagnostics; using System.Text; using System.Threading; using System.Windows.Forms; public static class CommandExecutor { public delegate void OutputHandler(string line); public static int Run(string workingDirectory, string command, string arguments, OutputHandler outputHandler, bool hideWindow = true) { int exitCode = -1; // Initialize to an invalid value try { using (var process = new Process()) { process.StartInfo.FileName = "cmd.exe"; process.StartInfo.WorkingDirectory = workingDirectory; process.StartInfo.Arguments = $"/c \"{command} {arguments}\" 2>&1"; // Redirect stderr to stdout process.StartInfo.CreateNoWindow = hideWindow; process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; if (outputHandler != null) { process.OutputDataReceived += (sender, e) => { if (e.Data != null) { outputHandler(e.Data); } }; process.ErrorDataReceived += (sender, e) => { if (e.Data != null) { outputHandler($"Error: {e.Data}"); //Clearly mark error messages } }; } process.Start(); if (outputHandler != null) { process.BeginOutputReadLine(); process.BeginErrorReadLine(); //Begin reading error stream process.WaitForExit(); } else { process.WaitForExit(); } exitCode = process.ExitCode; } } catch (Exception ex) { MessageBox.Show($"An error occurred: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } return exitCode; } public static string GetOutput(string workingDirectory, string command, string arguments) { StringBuilder output = new StringBuilder(); Run(workingDirectory, command, arguments, line => output.AppendLine(line)); return output.ToString(); } } public partial class Form1 : Form { private TextBox txtOutput; //Declare TextBox public Form1() { InitializeComponent(); txtOutput = new TextBox { Dock = DockStyle.Fill, Multiline = true, ScrollBars = ScrollBars.Both }; Controls.Add(txtOutput); // Add the TextBox to the form //Add a button (btnExecute) to your form in the designer. } private void btnExecute_Click(object sender, EventArgs e) { //Get command and arguments from your textboxes (e.g., textBoxCommand, textBoxArguments) string command = textBoxCommand.Text; string arguments = textBoxArguments.Text; CommandExecutor.Run(@"C:\", command, arguments, line => { if (txtOutput.InvokeRequired) { txtOutput.Invoke(new MethodInvoker(() => txtOutput.AppendText(line + Environment.NewLine))); } else { txtOutput.AppendText(line + Environment.NewLine); } }); } }</code>
>
try-catch
CommandExecutor
workingDirectory
InvokeRequired
>使用Environment.NewLine
使用字符串插值进行清洁参数构建。以上是如何在 Windows 窗体文本框中显示实时命令输出?的详细内容。更多信息请关注PHP中文网其他相关文章!