通过线程创建控件

本文关键字:控件 创建 线程 | 更新日期: 2023-09-27 18:34:39

是否可以通过类似于此非工作代码的线程来创建控件?

Thread t1 = new Thread(() => Panel p = create_control(param1,param2);
t1.start();
this.Controls.Add(p);

create_control类类似于:

Panel p = new Panel();
p.Location...
p.Size...
p.Name...
return p;

通过线程创建控件

我想

这就是你要问的,

首先,你有一个类,它可以创建一个带有参数的控件

public class CreateControl
{
    public Control Create(string name, Point location, Size size)
    {
        Panel p = new Panel();
        p.Name = name;
        p.Location = location;
        p.Size = size;
        p.BackColor = Color.Red;
        return p;
    }
}

然后在 winform 中,您可以使用线程创建控件,并且在使用 Tinwor 建议的窗体的 invoke 方法将控件添加到窗体时,需要避免交叉线程操作异常。

public partial class Form1 : Form
{
    public delegate void AddToControl(Control control);
    public AddToControl MyAddToControl;
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Thread t1 = new Thread((ThreadStart)delegate
                                                {
                                                    CreateControl c = new CreateControl();
                                                    Panel p = (Panel)c.Create("panel_1", new Point(10, 10), new Size(100, 100));
                                                    AddControlToControls(this, p);
                                                });
        t1.Start();
    }
    public void AddControlToControls(Control parent, Control control)
    {
        MyAddToControl = new AddToControl(this.AddControl);
        parent.Invoke(this.MyAddToControl, control);
    }
    public void AddControl(Control control)
    {
        this.Controls.Add(control);
    }
}

所以基本上是可以做到的。我相信代码可以改进以使其更简洁。希望这有帮助。