如果有其他条件。关闭?

时间:2013-06-10 10:06:13

标签: c# winforms if-statement

我有2个表格1mdiparent,1child

让我们说mdiparent = Form1然后是child = Form2。

我在Form1中使用New按钮调用childform(Form2),如:

private void newDocument_ItemClick(object sender, ClickEventArgs e)
        {
            Form2 formChild = new Form2();
            Form2.Show()
}

现在我的问题是if else条件:如果Form2 ==关闭?

类似的东西:

if (Form2.Close == true){ //condition }

or if (Form2 == Close){ //condition }

但我知道它不是正确的代码。所以希望你能帮助我:)谢谢。

6 个答案:

答案 0 :(得分:2)

如果我正确理解您的问题,您希望系统在关闭Form2时收到通知,以便您可以应用一些内部逻辑来避免重新打开子表单并对主界面应用某种更改。登记/> 如果这是您的问题,那么当您打开Form2时,可以直接在Form1的代码中为Form2的FormClosing事件添加事件处理程序

// Flag to keep the state open/close of the child form
private bool childClosed = true;

private void newDocument_ItemClick(object sender, ClickEventArgs e)
{
    if(childClosed == true)
    {
        Form2 formChild = new Form2();
        // Setup the event handler form the Form2 closing directly here in the MDI
        formChild.FormClosing += new FormClosingEventHandler(myFormClosing);
        formChild.Show();

        // set the flag to avoid the reopening
        childClosed = false;
    }
}

// Now, when the formChild closes, you will receive the event directly here in the MDI
private void myFormClosing(object sender, FormClosingEventArgs e)
{
    // The child form is closing......
    // Do your update here, but first check the close reason

    if(e.CloseReason == CloseReason.UserClosing)
    {
       ......
       // reset the flag so you could reopen the child if needed
       childClosed = true;
    }
}

答案 1 :(得分:1)

您可能希望使用Form.FormClosed事件或Form.FormClosing事件。可能是前者,因为你真的不想与表格的结束进行互动。

你会创建一个方法,并在事件被触发时调用它,这可以做任何你想做的事情(比如隐藏按钮等)。

有关formclosed事件的详细信息,请参阅http://msdn.microsoft.com/en-us/library/system.windows.forms.form.formclosed.aspx

答案 2 :(得分:1)

当表格关闭时,它也会被处理掉。因此,只需通过以下代码检查它是否被处理:

Form2 formChild = new Form2();
// ...
if (formChild.IsDisposed) {
    // Do someting
}

答案 3 :(得分:0)

正如@ V4Vendetta指出:有一个FormClosing事件(在表单关闭之前调用。用于告诉用户“你还没有保存”)和一个FormClosed事件(称为表格结束后。)

public class Form2 : Form
{
    public bool hasClosed;

    private void Form2_FormClosed(object sender, FormClosedEventArgs e)
    {
        hasClosed = true;
    }
}

有了这个,你可以做到

if (formChild.hasClosed)
    // do something

答案 4 :(得分:0)

采用这种方法是错误的,表单2在按钮单击事件中初始化,因此,您假设表单对象不可用。

如果你想改变这个顺序,那么表格应该在其他地方初始化,就像Form 1的构造函数一样。

private Form2 form2;
public Form1()
{
    form2 = new Form2();
}

private void newDocument_ItemClick(object sender, ClickEventArgs e)
{
    if(!form2.Visible)
    {
        form2.Show();
    }else
    {
        form2.Hide();
    }
}

隐藏表单与关闭表单不同,如果你真的打开并关闭form2并根据它执行某些操作,那么你应该在触发form2结束事件时在父表单上设置一个属性,为此,您必须将父窗体作为参数传递给form2构造函数。

答案 5 :(得分:0)

您可以借助以下代码检查

foreach (Form f in Application.OpenForms)
{
        if (f.Text == formName)
        {
                    IsOpen = true;
                    break;
        }
}
if(!IsOpen)
{....do your code....}