1
votes

I created a very basic splash screen for a WinForm application.

The application has to connect to a database on loading, so I created a OnLoad method like this one:

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.

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.

3
Would help if we knew what those functions do exactly(show and close)Samy Arous

3 Answers

4
votes

Try calling Activate after SplashScreen.CloseSplashScreen();

MainForm.Activate();
2
votes

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).

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;
    }
}
-1
votes

Register your Form for the OnShown event and call set the TopMost flag to true:

form1.OnShown += OnShownHandler;

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