黑马程序员技术交流社区
标题:
为什么一个线程中的不能为 另一个线程中控件的父类?
[打印本页]
作者:
shangxin
时间:
2014-3-19 20:11
标题:
为什么一个线程中的不能为 另一个线程中控件的父类?
本帖最后由 shangxin 于 2014-3-20 10:35 编辑
为什么一个线程中的不能为 另一个线程中控件的父类?该如何做呢?
作者:
threederek
时间:
2014-3-19 20:17
的确会这样的,在某个线程中创建的控件不能以另一个线程中创建的控件作为parent,原先的设计就是这样的(即by design的)。
解决方法是用Control.Invoke。下面是一段例子代码:
private void menuItemFoo_Click(object sender, System.EventArgs e)
{
System.Threading.Thread thread=new System.Threading.Thread(new System.Threading.ThreadStart(this.Foo));
thread.Start();
}
public delegate void MyDelegate(Form form);
System.Windows.Forms.Form childForm;
private void AddMdiChild(Form form)
{
form.MdiParent=this;
form.Show();
}
private void Foo()
{
childForm=new Form();
//childForm.MdiParent=this; //直接调用会出错
//childForm.Show();
this.Invoke(new MyDelegate(this.AddMdiChild),new object[]{childForm});
}
复制代码
作者:
shangxin
时间:
2014-3-19 20:33
Thank You!
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2