namespace WindowsFormsApp1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { // 开启新线程添加控件 Thread thread = new Thread(new ThreadStart(AddControls)); thread.Start(); } private void AddControls() { // 在新线程中添加控件 Button button = new Button(); button.Text = "New Button"; button.Location = new Point(100, 100); // InvokeRequired 用于检查是否在主线程中 // 如果不在主线程,则使用Invoke在主线程中执行 if (this.InvokeRequired) { this.Invoke(new Action<Button>(AddControl), new object[] { button }); } else { this.Controls.Add(button); } } private void AddControl(Button button) { this.Controls.Add(button); } } }
winfrom多线程添加控件有案列
猜你喜欢
转载自blog.csdn.net/zhang8593/article/details/130430587
今日推荐
周排行