c# - 如果第二个表格打开,请放在前面

我在 Form1 上有一个按钮,如果 Form2 没有打开,它会打开 Form2(Leaderboard)。我想要做的是:单击按钮,如果 Form2 已关闭,则打开 Form2。否则 Form2 已打开,请将 Form2 置于最前面。

使用下面的代码,当 leaderboardOpen == true; 什么都不做时单击按钮。

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

回答1

保留对您的 Leaderboard 实例本身的引用,而不是布尔值:

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

回答2

让它与下面的代码一起工作。

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

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

回答3

这是我的工作代码

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

如果排行榜表单已关闭,请确保制作 leaderboardOpened = false;

相似文章

最新文章