C#窗体在运行时添加控件



你好,我在运行时很难将控件添加到表单中。

static Form1 f2 = new Form1();
async public static void startTimer()
{
//await Task.Run(() => f2.ShowDialog());
stopWatch.Start();
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
aTimer.Interval = 50;
aTimer.Enabled = true;
await Task.Run(() => f2.ShowDialog());
}
public static void splitTime()
{
TextBox txtRun = new TextBox();
txtRun.Name = "txtDynamic";
txtRun.Location = new System.Drawing.Point(20, 18 + (20 * 2));
txtRun.Size = new System.Drawing.Size(200, 25);
f2.Controls.Add(txtRun);        
}

知道为什么会失败吗?我认为是因为异步,但不知道如何解决它。

this.BeginInvoke((Action)delegate ()
{
TextBox txtRun = new TextBox();
txtRun.Name = "txtDynamic";
txtRun.Location = new System.Drawing.Point(20, 18 + (20 * 2));
txtRun.Size = new System.Drawing.Size(200, 25);
f2.Controls.Add(txtRun);    
});

最新更新