繁体   English   中英

从另一个'表单'关闭'表单'

[英]Closing a 'form' from another 'form'

我开发了一个应用程序,我使用Windows窗体作为启动画面。 显示启动画面后,我创建了一个新线程来触发新窗体。 现在我想在我的表单显示后关闭启动画面。

我搜索了我的查询,许多讨论但找不到我想要的东西。

请指导一下。

谢谢。

只要您对第一个表单有一些引用,就可以在另一个表单上调用Close()方法。 因此,当您创建第二个表单时,请为其指定启动画面。 然后将处理程序附加到Shown事件并在启动屏幕上调用close。

为了解决跨线程问题,您需要创建一个名为ThreadSafeClose的方法,并按如下方式定义。 然后调用该方法而不是.Close()

public void ThreadSafeClose() {
        if(this.InvokeRequired) {
            this.Invoke(new MethodInvoker(this.Close));
        }
    }

要关闭表单,您需要有一个指向此表单的链接。 最简单的方法是向Program中的Program对象添加一个新属性,该属性是静态的,并且可以在任何地方使用。 只需修改Program.cs文件以使Program类公开并添加适当的引用:

public static class Program
{
    ///This is your splash screen
    public static Form1 MySplashScreen = new Form1();

    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        /// This is how you run your main form
        Application.Run(MySplashScreen);
    }
}

然后在表单中,您可以使用以下语法轻松关闭启动画面窗体:

Program.MySplashScreen.Close();

编辑:在WinForms中只有一个GUI线程,所以只要你从另一个表单中执行关闭它应该是安全的。 如果要从GUI生成的工作线程关闭表单,请使用以下代码(这应该引用您的第二个表单):

this.Invoke((MethodInvoker)delegate {
            Program.MySplashScreen.Close();
});

通常您不需要新线程。 但是一旦你拥有它,你可以通过在两个线程之间共享bool值(将其命名为closeSplash)来实现。

在启动窗体上放置一个计时器,每秒检查closeSplash的值。 当closeSplash为true时,只需调用Splash表单的Close()方法即可。

如果您选择关闭另一个线程的启动,请看这个

我有一个hacky方法,我使用..虽然可能不是最好的事情。 在初始屏幕窗体中声明一个自身的静态实例。

public static SplashForm splashInstance;

然后在splashform的构造函数中,您可以赋值“this”。

SplashForm.splashInstance = this;

您现在可以从应用程序中的任何位置调用SplashForm.splashInstance.Close()。

并不需要一个单独的线程只是在一段时间内显示“闪屏”。 实际上,有更好的方法可以设计您的类,使这样做更容易完成。 在这里不使用计时器或使用单独的线程不是正确的解决方案恕我直言。 我建议你尝试这样做:

public class SplashScreen : Form
{
    // add a timer to your form with desired interval to show

    protected override void OnShown(EventArgs e)
    {
        displayTimer.Start();
        base.OnShown(e);
    }

    private void displayTimer_Tick(object sender, EventArgs e)
    {
        this.Close();
    }
}

public class MainForm : Form
{
    protected override void OnLoad(EventArgs e)
    {
        // splash screen will be shown before your main form tries to show itself
        using (var splash = new SplashScreen())
            splash.ShowDialog();
        base.OnLoad(e);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM