在项目中需要用到在子窗体的操作都记录在主窗体的控件中,比如richTextBox控件
1,首先在主窗体的designer代码页将该控件的属性设置为public,默认为private的
2,在主窗体页面声明变量,如下: public static mainForm form;然后再在该窗体类的构造方法中加上:form=this;
3,再在子窗体中直接引用就行了,无论控件还是方法都可以引用了,前提一定要是public
mainForm.form.RunLog(mainForm.form.richTextBox1, "数据库连接错误:"+ ex.ToString(), 0);
调用的控件一定要写委托,不然跨线程调用是会报错的
public delegate void SetRunLogEventHandler(RichTextBox rtb, string str, int i);
public void RunLog(RichTextBox rtb, string str, int i)
{
SetRunLogEventHandler aa = (RichTextBox rtb1, string str1, int i1) =>
{
if (i1 == 0)
{
rtb.SelectionColor = Color.Black;
}
if (i1 == 1)
{
rtb.SelectionColor = Color.FromArgb(192, 0, 0);
rtb.SelectionColor = Color.Red;
}
string time1 = DateTime.Now.ToString("HH:mm:ss");
string date1 = DateTime.Now.ToString("yyyy/MM/dd");
rtb.SelectionStart = rtb.TextLength;
rtb.ScrollToCaret();
rtb.AppendText(date1 + " " + time1 + " " + str + "\n");
//fr1.GetLog(str1, i);
new Thread(() => { myText.WriteStr(date1 + " " + time1 + " " + str1); }) { IsBackground = true }.Start();
};
rtb.Invoke(aa, rtb, str, i);
}