从C#上的函数处理程序访问表单控件

时间:2018-05-19 10:22:58

标签: c# multithreading forms ms-access

我在C#上创建了一个交互式shell,但我不知道如何访问我的表单控件并将接收到的值分配给我的文本框,我知道线程无法访问UI线程,但是在此如果我似乎无法解决问题,那个shell中会有很多输入和输出,我想确保向用户显示所有内容。

 public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Process process = new Process();
            process.StartInfo.FileName = "echoo.exe";
            process.StartInfo.Arguments = "";
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.RedirectStandardError = true;


            process.ErrorDataReceived += new DataReceivedEventHandler(OutputHandler);

            process.StartInfo.RedirectStandardInput = true;

            process.Start();

            StreamWriter sw = process.StandardInput;

            process.BeginOutputReadLine();
            process.BeginErrorReadLine();

            sw.WriteLine("sent");
            process.WaitForExit();

        }
        static void OutputHandler(object sendingProcess, DataReceivedEventArgs outLine)
        {

            Form1.textBox1.Text = outLine.Data;
        }


    }

1 个答案:

答案 0 :(得分:1)

如果你在你的二传手中写下这个:

static void OutputHandler(object sendingProcess, DataReceivedEventArgs outLine)
{
    if(textBox1.InvokeRequired)
    {
        textBox1.BeginInvoke((MethodInvoker) delegate() {textBox1.Text = outLine.Data;});    
    }
    else
    {
        textBox1.Text = outLine.Data;
    }
}

它会将该集强制转换为UI线程。我从这个问题中找到了这个:stack question