C#批处理文件输出问题

本文关键字:出问题 输出 批处理文件 | 更新日期: 2023-09-27 17:58:29

我一直在为Minecraft服务器开发管理器应用程序,当我运行程序时,控制台会显示并消失,如果我手动运行它,它运行时不会出现任何问题。批处理文件代码:

java -Xmx1024M -jar craftbukkit-1.7.2-R0.3.jar -o false

我的完整代码(MessageBox是波兰语的,因为我来自波兰,但稍后我将添加对其他语言的支持):

using System;
using System.IO;
using System.Windows.Forms;
using System.Diagnostics;
namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        public Process server;
        private Boolean runServer()
        {
            if (!File.Exists(textBox2.Text))
            {
                MessageBox.Show("Brak określonej ścieżki dostępu! (" + textBox2.Text + ")", "Błąd", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
            Process process = new Process
            {
                StartInfo =
                {
                    FileName = textBox2.Text,
                    //Arguments = textBox3.Text,
                    UseShellExecute = false,
                    RedirectStandardOutput = true,
                    CreateNoWindow = false,
                }
            };
            process.OutputDataReceived += new DataReceivedEventHandler(server_outputDataReceived);
            process.ErrorDataReceived += new DataReceivedEventHandler(server_outputDataReceived);
            server = process;
            if (process.Start())
                return true;
            else
            {
                MessageBox.Show("Nie można włączyć serwera!", "Błąd", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
        }
        private String ReadFile(String filename, int line)
        {
            StreamReader reader = new StreamReader(filename);
            for (int i = 0; i < line; i++)
            {
                reader.ReadLine();
            }
            return reader.ReadLine();
        }
        private void ReloadOPs()
        {
            if (!File.Exists(textBox1.Text))
            {
                MessageBox.Show("Sciezka dostępu do pliku z listą graczy posiadających OP nie istnieje! (" + textBox1.Text + ")", "Błąd", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                tabControl1.SelectedTab = tabPageOptions;
                textBox1.SelectAll();
                return;
            }
            String line = ReadFile(textBox1.Text, 0);
            comboBox1.Items.Clear();
            for (int i = 1; i < File.ReadAllLines(textBox1.Text).Length; i++)
            {
                if (!String.IsNullOrWhiteSpace(ReadFile(textBox1.Text, i)))
                {
                    comboBox1.Items.Add(line);
                    line = ReadFile(textBox1.Text, i);
                }
            }
            MessageBox.Show("Lista graczy z OP, została odświeżona.");
        }
        // OPs combobox (OPs)
        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            groupBox1.Text = comboBox1.SelectedItem.ToString();
            groupBox1.Visible = true;
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            textBox1.Text = Application.StartupPath.ToString() + @"'ops.txt";
            ReloadOPs();
        }
        // Reload OPs button (OPs)
        private void button1_Click(object sender, EventArgs e)
        {
            ReloadOPs();
        }

        // Save button (Options)
        private void button4_Click(object sender, EventArgs e)
        {
        }
        private void server_outputDataReceived(object sender, DataReceivedEventArgs e)
        {
            addConsoleMessage(e.Data.ToString(), true);
        }
        // Run server button (Menu)
        private void button5_Click(object sender, EventArgs e)
        {
            if (!runServer())
                return;
            server.BeginOutputReadLine();
            button6.Enabled = true;
        }
        // Stop server button (Menu)
        private void button6_Click(object sender, EventArgs e)
        {
            if(!server.HasExited)
                server.Kill();
            button6.Enabled = false;
        }
        private void addConsoleMessage(String message, Boolean refresh)
        {
            listBox1.Items.Add(message);
            if (refresh)
                listBox1.Refresh();
        }
    }
}

我的问题是程序崩溃,因为未处理InvaildOperationException(addConsoleMessage中的listBox1.Items.Add(message))。外部错误信息:线程之间的操作无效:控件"listBox1"是从创建它的线程以外的线程访问的。

C#批处理文件输出问题

您无法更新UI窗体后台线程。试试这个

WPF

    private void server_outputDataReceived(object sender, DataReceivedEventArgs e)
    {
        Dispatcher.CurrentDispatcher.Invoke(DispatcherPriority.Normal, () =>
                {
                     addConsoleMessage(e.Data.ToString(), true);
                });
    }

更新

在WinForms中,Invoke/BeginInvoke方法直接在控件对象上,正如您从System.Windows.Forms.control的文档中看到的那样。因此,您可以使用listBox1.BeginInvoke(…)作为示例。