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()));
}
}
程序说错误:
RichTextBox rtb =(RichTextBox)tabControl.SelectedTab.Tag; <<附加信息:跨线程操作无效:控制'tabControl'从其创建的线程以外的线程访问。
我无法解决它
可以帮帮我吗?
三江源
答案 0 :(得分:0)
试试这个:
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();
}));
}