C#中Timer控件和多线程导致的窗体无法正常显示问题

2025-05-03 16:53:12
推荐回答(1个)
回答1:

这里是一段使用timer执行绘制UI的方法:

public partial class Form1 : Form
{
    public Form1()
    {
        // Create a timer that will call the ShowTime method every second. 
        var timer = new System.Threading.Timer(ShowTime, null, 0, 1000);           
    }
    private void ShowTime(object x)
    {
        // Don't do anything if the form's handle hasn't been created  
        // or the form has been disposed. 
        if (!this.IsHandleCreated && !this.IsDisposed) return;
        // Invoke an anonymous method on the thread of the form. 
        this.Invoke((MethodInvoker) delegate
        {
            // Show the current time in the form's title bar. 
            this.Text = DateTime.Now.ToLongTimeString();
        });
    }
}

所以你可以试试:

void showrm2()        {            
this.Invoke((MethodInvoker) delegate       
{           
  // Show the current time in the form's title bar.            
  Form2 fm = new Form2();           
  Application.Run(fm);        
  });
}