StackOverflowException when trying to create a form that starts with

My problem is simple. I have this new form and I am just coding this:

    public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        this.Resize += new EventHandler(Form1_Resize);

        this.WindowState = FormWindowState.Minimized;
    }

    private void Form1_Resize(object sender, EventArgs e)
    {
        if (WindowState == FormWindowState.Minimized)
        {
            ShowInTaskbar = false;
        }
        else if (WindowState == FormWindowState.Normal)
        {
            ShowInTaskbar = true;
        }
    }
}

I want this form to start shrinking, and I want to show the taskbar icon only when the form is not minimized. But when I run it, I get StackOverflowException. I think that ShowInTaskbar = falsecalls the resize method.

+3
source share
2 answers

Place automatic minimization in the "Load" event instead of the constructor.

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        this.Resize += new EventHandler(Form1_Resize);
        this.Load += new EventHandler(Form1_Load);

    }

    void Form1_Load(object sender, EventArgs e)
    {
        WindowState = FormWindowState.Minimized;
    }

    private void Form1_Resize(object sender, EventArgs e)
    {
        if (WindowState == FormWindowState.Minimized)
        {
            ShowInTaskbar = false;
        }
        else if (WindowState == FormWindowState.Normal)
        {
            ShowInTaskbar = true;
        }
    }
}

I'm not quite sure why this prevents stack overflows, but as soon as I find out I will update the answer. I tested it after reproducing the problem and can confirm that it works!

+3
source

. , .

( ) , ( , ) - bool, ​​ true, , , , , .

0

All Articles