简体   繁体   English

WinForm启动画面和焦点

[英]WinForm splash screen and focus

I created a very basic splash screen for a WinForm application. 我为WinForm应用程序创建了一个非常基本的启动屏幕。

The application has to connect to a database on loading, so I created a OnLoad method like this one: 该应用程序必须在加载时连接到数据库,所以我创建了一个像这样的OnLoad方法:

private void MainForm_OnLoad(object sender, EventArgs e)
{
    SplashScreen.ShowSplashScreen();
    PerformConnection();
    SplashScreen.CloseSplashScreen();
}

The splash screen is a simple form. 初始屏幕是一种简单的形式。 The ShowSplashScreen method creates the form and shows it up, the CloseSplashScreen closes the form. ShowSplashScreen方法创建并显示该窗体,CloseSplashScreen关闭该窗体。

Everything seems to work, except that when the splash screen closes, the main form loses the focus and is hidden by the previously selected window. 似乎一切正常,除了启动屏幕关闭时,主窗体失去焦点并被先前选择的窗口隐藏。

I do not understand why, nor I know how to solve this problem. 我不明白为什么,也不知道如何解决这个问题。

尝试在SplashScreen.CloseSplashScreen();之后调用Activate SplashScreen.CloseSplashScreen();

MainForm.Activate();

You should do it differentlly. 您应该以不同的方式进行操作。 Splash screen could be called before main form, and this is how you can do it (code bellow). 启动画面可以在主窗体之前调用,这是您可以执行的操作(下面的代码)。 By using DialogResult.OK, will return code back to Program class, and continue with creating (and opening) Form1 (your main form). 通过使用DialogResult.OK,将代码返回给Program类,并继续创建(并打开)Form1(您的主窗体)。

static class Program
{
    [STAThread]
    static void Main()
    {
        using (SplashScreen sp = new SplashScreen())
        {
            sp.StartPosition = FormStartPosition.CenterScreen;
            if (login.ShowDialog() == DialogResult.OK)
            {
                Application.Run(new Form1()); 
            }
        }
    }
}


public partial class SplashScreen : Form
{
    public SplashScreen()
    {
        InitializeComponent();
        DoTheWork();
    }

    private void DoTheWork()
    {
        //...
        //and on the end
        this.DialogResult = DialogResult.OK;
    }
}

Register your Form for the OnShown event and call set the TopMost flag to true: OnShown事件注册您的Form ,然后调用将TopMost标志设置为true:

form1.OnShown += OnShownHandler;

private void OnShownHandler(EventArgs e)
{
    form1.TopMost = true;
}

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

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