简体   繁体   中英

If second form is open, bring to front

I have a button on Form1 that opens Form2(Leaderboard) if Form2 is not open. What I am trying to do is: On Button click, if Form2 is closed, open Form2. Else Form2 is open, bring Form2 to front.
With the below code, clicking the button when leaderboardOpen == true; does nothing at all.

public static bool leaderboardOpen = false;
    private void leaderButton_Click(object sender, EventArgs e)
        {
            if (leaderboardOpen == false)
            {
                Leaderboard leaderboard = new Leaderboard();
                leaderboard.Show();
                leaderboardOpen = true;
            }
            else
            {
                Leaderboard leaderboard = new Leaderboard();
                 //Tried the below
                //leaderboard.Focus();
                //leaderboard.BringToFront();
                //leaderboard.TopMost = true;
                //leaderboard.Activate();
            }
        }

Instead of a bool, keep a reference to your instance of Leaderboard itself:

private Leaderboard leader = null;
private void leaderButton_Click(object sender, EventArgs e)
{
    if (leader == null || leader.IsDisposed)
    {
        leader = new Leaderboard();
        leader.FormClosed += (s2, e2) => { leader = null; };
        leader.Show();
    }
    else
    {
        if (leader.WindowState == FormWindowState.Minimized)
        {
            leader.WindowState = FormWindowState.Normal;
        }
        leader.BringToFront();
    }            
}

Got it working with the below code.

private void leaderButton_Click(object sender, EventArgs e)
        {
            var form = Application.OpenForms.OfType<Leaderboard>().FirstOrDefault();

            if (form != null)
            {
                form.Activate();
            }
            else
            {
                new Leaderboard().Show();
            }
        }

Here is a working code for me

public static bool leaderboardOpen = false;
public static Leaderboard? leaderboardForm = null;
private void leaderButton_Click(object sender, EventArgs e)
{
    if (!leaderboardOpened || leaderboardForm is null)
    {
        // Initialize Leaderboard form if it doesn't exist
        leaderboardForm = new Leaderboard();
        leaderboardForm.Show();
        leaderboardOpened = true;
    }
    else
    {
        // Focus on the form
        leaderboardForm.Focus();
    }
}

Make sure to make leaderboardOpened = false; if the Leaderboard form is closed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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