关闭一个特定的WinForm?

时间:2010-07-12 20:33:13

标签: c# winforms

假设我以下列方式打开表单:

FormSomething FormSomething = new FormSomething(SomethingId);
FormSomething.Show();

在我的代码中,有很多FormSomething可能会立即打开。如何关闭FormSomething的特定实例?

FormSomething的每个实例都有一个与之关联的ID。

编辑:我想我真正想要的是能够外部关闭FormSomething的特定实例。

我真的很感激任何提示! :d

2 个答案:

答案 0 :(得分:3)

您可以调用Form类上的Close方法。

听起来你只需要保留一份已打开的表格列表,以便日后可以参考:

    List<FormSomthing> _SomethingForms = new List<FormSomething>();

    void DisplaySomething()
    {
        FormSomething FormSomething = new FormSomething(SomethingId);
        _SomethingForms.Add(FormSomething);
        FormSomething.Show();
    }

    void CloseThatSucka(int somethingId)
    {
        // You might as well use a Dictionary instead of a List (unless you just hate dictionaries...)
        var form = _SomethingForms.Find(frm => frm.SomethingId == somethingId);
        if(form != null)
        {
            form.Close();
            _SomethingForms.Remove(form);
        }
    }

答案 1 :(得分:2)

跟踪它们。字典是自然的集合对象。例如:

    Dictionary<int, Form2> instances = new Dictionary<int, Form2>();

    public void OpenForm(int id) {
        if (instances.ContainsKey(id)) {
            var frm = instances[id];
            frm.WindowState = FormWindowState.Normal;
            frm.Focus();
        }
        else {
            var frm = new Form2(id);
            instances.Add(id, frm);
            frm.FormClosed += delegate { instances.Remove(id); };
            frm.Show();
        }
    }