Home > Mobile >  If second form is open, bring to front
If second form is open, bring to front

Time:05-19

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

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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.

  •  Tags:  
  • c#
  • Related