加载另一个表单后关闭表单

本文关键字:表单 加载 另一个 | 更新日期: 2023-09-27 17:58:44

我打算开发一个简单的应用程序,其中有一个主表单和几个子表单。

首先,我创建了加载表单(加载表单有2个IMG和1个标签,1个IMG I加载GIF),该表单只工作几秒钟。接下来,我创建另一个表单(该表单应该是登录表单)。现在我需要在加载或显示第二个表单后关闭第一个表单。这是我的第一个表单中的代码:

public partial class Loading : Form
{
    private static System.Timers.Timer aTimer;
    public Loading()
    {
        InitializeComponent();
        this.FormBorderStyle = FormBorderStyle.None;
        Region = System.Drawing.Region.FromHrgn(CreateRoundRectRgn(0, 0, Width, Height, 10, 10));
        aTimer = new System.Timers.Timer();
        Random rnd = new Random();
        int loading_time = rnd.Next(2500, 4200);
        aTimer.Interval = loading_time;
        aTimer.SynchronizingObject = this; //////////////
        aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
        aTimer.Enabled = true;
    }


    private void OnTimedEvent(object source, ElapsedEventArgs e)
    {
       // New Form run 1st try
        login form2 = new login();
        form2.ShowDialog();
      // New Form run 2nd try
        Application.Run(new login());
      // Loading form closing 1st try
      this.Close();
         // Loading form closing 2nd try
      Loading.Close();

我还试着用第二个窗体上的按钮关闭第一个窗体,但没有成功。提前感谢

加载另一个表单后关闭表单

您不能从创建控件的线程以外的线程访问控件。

OnTimedEvent是在主线程以外的线程中调用的。

编辑:试试这个

aTimer.SynchronizingObject = this;

这应该使OnTimedEvend在创建表单的线程上运行。