Cristiano
Cristiano

Reputation: 876

WinForm splash screen and focus

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.

Upvotes: 1

Views: 1958

Answers (3)

SwDevMan81
SwDevMan81

Reputation: 50018

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

Upvotes: -1

Mitja Bonca
Mitja Bonca

Reputation: 4546

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

Upvotes: 2

Icarus
Icarus

Reputation: 63962

Try calling Activate after SplashScreen.CloseSplashScreen();

MainForm.Activate();

Upvotes: 4

Related Questions