0
    private void btn_Run_Click(object sender, EventArgs e)
    {
        // Run CMD
        AddTab();
        StartCMD();
    }

    private void AddTab()
    {
        // Add TabPage
        TabPage newTab = new TabPage((string)cbConfig.SelectedItem);

        //3rd EDIT: add a control to each newTab
        RichTextBox rtb = new RichTextBox();

        rtb.Dock = DockStyle.Fill;
        rtb.ScrollBars = System.Windows.Forms.RichTextBoxScrollBars.Vertical;
        rtb.BorderStyle = System.Windows.Forms.BorderStyle.None;
        rtb.BackColor = System.Drawing.Color.White;
        rtb.ReadOnly = true;

        newTab.Controls.Add(rtb);

        tabControl.Controls.Add(newTab);
        //EDIT: select new tab when created
        tabControl.SelectTab(newTab);
    }

    private void StartCMD()
    {

        string command = "c:\dir";
        // Start connect to process
        ProcessStartInfo psi = new ProcessStartInfo("cmd.exe", "/C " + command); // 
        psi.UseShellExecute = false;
        psi.RedirectStandardOutput = true; 
        psi.RedirectStandardInput = true; 
        psi.CreateNoWindow = true; 

        var proc = Process.Start(psi); 

        proc.OutputDataReceived += build_ErrorDataReceived;
        proc.BeginOutputReadLine();
    }

    private void build_ErrorDataReceived(object sender, DataReceivedEventArgs e)
    {
        string strMessage = e.Data;
        if (tabControl.InvokeRequired)
        {
                RichTextBox rtb = (RichTextBox)tabControl.SelectedTab.Tag;
                rtb.Invoke(new Action(() => rtb.AppendText(strMessage + Environment.NewLine)));
                rtb.Invoke(new Action(() => rtb.Select(rtb.Text.Length - 1, 0)));
                rtb.Invoke(new Action(() => rtb.ScrollToCaret()));
        }
    }

Program say error:

RichTextBox rtb = (RichTextBox)tabControl.SelectedTab.Tag; << Additional information: Cross-thread operation not valid: Control 'tabControl' accessed from a thread other than the thread it was created on.

i can't fix it

Can help me ?

thankyou

4

1 回答 1

0

Try this:

if (tabControl.InvokeRequired) {
     tabControl.Invoke(new Action(()=>{
        RichTextBox rtb = (RichTextBox)tabControl.SelectedTab.Tag;
        rtb.AppendText(strMessage + Environment.NewLine);
         rtb.Select(rtb.Text.Length - 1, 0);
         rtb.ScrollToCaret();
     }));
}
于 2013-09-21T04:12:42.733 回答