要在WPF窗体中运行命令行,你可以使用Process类启动命令行进程,并将其输出重定向到WPF应用程序中。以下是一个简单的示例代码,它演示了如何启动cmd.exe并在WPF窗体中显示其输出:

using System.Diagnostics;
using System.IO;

// ...

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        // Create a new ProcessStartInfo object and set the command and arguments
        ProcessStartInfo startInfo = new ProcessStartInfo();
        startInfo.FileName = "cmd.exe";
        startInfo.Arguments = "/c dir"; // Replace "dir" with your command

        // Set the process options
        startInfo.UseShellExecute = false;
        startInfo.RedirectStandardOutput = true;
        startInfo.CreateNoWindow = true;

        // Create the process and start it
        Process process = new Process();
        process.StartInfo = startInfo;
        process.OutputDataReceived += new DataReceivedEventHandler(OutputDataReceived);
        process.Start();
        process.BeginOutputReadLine();
    }

    private void OutputDataReceived(object sender, DataReceivedEventArgs e)
    {
        // Write the output to the console
        Console.WriteLine(e.Data);

        // Update the UI on the UI thread
        this.Dispatcher.Invoke(() =>
        {
            this.OutputTextBlock.Text += e.Data + Environment.NewLine;
        });
    }
}

在这个例子中,我们创建了一个WPF窗体,并在点击按钮时启动cmd.exe进程并将其输出重定向到窗体中。我们使用了ProcessStartInfo类来设置进程选项,并将OutputDataReceived事件附加到进程对象上。在OutputDataReceived事件处理程序中,我们使用Dispatcher对象将输出添加到TextBlock控件中,并在UI线程上更新UI。



如果您对C#游戏开发感兴趣,可以扫下面二维码加入我们的QQ群来一起学习交流

原创文章,转载请注明本文链接地址(违者必究):C#如何让命令行在WPF窗体里面运行