-1

I have these classes :

internal partial class FBase : Form
{
    public FBase() { InitializeComponent(); }

    public FBase(bool owner) : this()
    {
        if (!owner) { this.Opacity = 0; Load += (s, e) => Close(); }
    }
}

internal partial class Form1 : FBase
{
    public Form1(bool owner) : base(owner) { InitializeComponent(); }
}

This code works (does not show Form1):

Form1 f = new Form1(false);
if(f != null) { f.MdiParent = parent; f.Show(); }

But this does not work (shows Form1):

OpenSingleMdiChild(() => new Form1(false));

This is the implementation of OpenSingleMdiChild:

public static void OpenSingleMdiChild<T>(this Form parent, Func<T> factory) where T : Form
{
    T f = null;

    foreach (Form c in parent.MdiChildren) if (c.GetType() == typeof(T)) {  f = c; break; }

    if (f == null) { f = factory(); f.MdiParent = parent; }

    f.Show(); f.Select();
}
geek
  • 346
  • 6
  • 14

1 Answers1

1

If I understand your question, you want to know why Form1 isn't shown. I think your FBase Constructor is the reason:

public FBase(bool owner) : this()
{
   if (!owner) { this.Opacity = 0; Load += (s, e) => Close(); }
}

There you tell the Load-Event to Close(); the Form. So it will directly be closed if owner is false. Further you should use some returns in your OpenSingleMdiChild-Method. Because this is really hard to read as @PeterBons points out.

Furthermore this code isn't very clear to me:

using (Form1 f = new Form1(false))
{
    if(f != null) { f.MdiParent = parent; f.Show(); }
}

You show a Form and directly destroy it? Why should someone do this?

I hope it answers your questions. Else ask some real questions please ;).

Sebi
  • 3,879
  • 2
  • 35
  • 62
  • I just want to close Form1 if owner=false – geek Nov 21 '16 at 08:59
  • @Jalil Please correct your question then. You write this: OpenSingleMdiChild(() => new Form1(false)); wouldn't be correct but you mean this i guess: OpenSingleMdiChild(() => new Form1(true)); – Sebi Nov 21 '16 at 09:16
  • my problem is that OpenSingleMdiChild(() => new Form1(false)) does not close Form1 !!! – geek Nov 21 '16 at 10:05
  • I just removed using(...) – geek Nov 21 '16 at 10:18
  • @Jalil Well now i understand your problem. I think your foreach finds a Form and so your factory(); is never called and the founded form is shown. – Sebi Nov 21 '16 at 10:33