0
public partial class MainMenu : Form
{
    public MainMenu()
    {
        InitializeComponent();
    }
    windowOne One;
    windowTwo Two;
    private void OneToolStripMenuItem_Click(object sender, EventArgs e)
    {
        if (One != null)
        {
            One.WindowState = FormWindowState.Normal;
            One.Focus();
        }
        else
        {
            One = new windowOne();
            One.MdiParent = this;
            One.FormClosed += (o, ea) => One = null;
            One.Show();
        }
    }

    private void TwoToolStripMenuItem_Click(object sender, EventArgs e)
    {
        if (Two != null)
        {
            TwoWindowState = Two.Normal;
            Two.Focus();
        }
        else
        {
            Two = new windowTwo();
            Two.MdiParent = this;
            Two.FormClosed += (o, ea) => Two = null;
            Two.Show();
        }
    }

我是 C# 的初学者,我正在开发窗口应用程序,我希望当 windowOne 打开时用户无法打开 windowTwo,我使用上面的代码来避免再次打开 windowOne 或 windowTwo ..

4

2 回答 2

1

您可以根据当时打开的窗口禁用任一菜单项 1/2,然后在您关闭窗口后再次启用它

menuItem1.Enabled = false;
于 2013-04-03T08:34:36.343 回答
0

在打开之前检查两个窗口,如果其中一个打开,则聚焦正确的一个。像这样:

if (One != null)
{
    One.WindowState = FormWindowState.Normal;
    One.Focus();
}
else if (Two != null)
{
    Two.WindowState = FormWindowState.Normal;
    Two.Focus();
}
else
{
    // Show the window
}

编辑:由于这些代码块完全相同,最好将它们分解到自己的方法中。

public bool IsWindowOpen()
{
    if (One != null)
    {
        One.WindowState = FormWindowState.Normal;
        One.Focus();
    }
    else if (Two != null)
    {
        Two.WindowState = FormWindowState.Normal;
        Two.Focus();
    }
    else
    {
        return false;
    }
    return true;
}

然后你可以像这样使用它:

if (!IsWindowOpen())
{
    // Open window
    Two = new windowTwo();
    Two.MdiParent = this;
    Two.FormClosed += (o, ea) => Two = null;
    Two.Show();
}
于 2013-04-03T08:32:35.473 回答