简体   繁体   中英

Use One Button To ShrinK & Grow

On my windows form, I want to add a button that will allow to grow and/or shrink the form. Can this be done with just one button or will I need to add in 2 separate buttons? This is the code I am using to grow on the button press. How can if the button is pressed again go to a smaller size?

private void buttonGrowShrink(object sender, EventArgs e)
{
  this.Size = new Size(320, 490);
}

How can I then use same button to shrink to a smaller size if the button is pressed again?

Two solutions are below. In both cases I also changed the text of the button so the user knows what will happen if they push it, but this would be optional.

One way would be to use a Boolean to track the current size of the form:

private bool formIsLarge = false;

private void buttonGrowShrink(object sender, EventArgs e)
{
    if (formIsLarge)
    {
        this.Size = new Size(160, 245);
        button1.Text = "Grow Form";
    }
    else
    {
        this.Size = new Size(320, 490);
        button1.Text = "Shrink Form";
    }

    formIsLarge = !formIsLarge;
}

Another way would be to just compare the current size of the form with the 'large' and 'small' sizes and change the size accordingly:

private void buttonGrowShrink(object sender, EventArgs e)
{
    var largeSize = new Size(320, 490);
    var smallSize = new Size(160, 245);

    if (this.Size.Width >= largeSize.Width || this.Size.Height >= largeSize.Height)
    {
        this.Size = smallSize;
        button1.Text = "Grow Form";
    }
    else
    {
        this.Size = largeSize;
        button1.Text = "Shrink Form";
    }
}

Here's an easy way to toggle between two sizes. Let's use (400,300) and (600,200) for example. Just add those values together to get a constant size. Then subtract the current size from that constant every time the button is clicked. Like so:

private void buttonGrowShrink(object sender, EventArgs e)
{
    this.Size = new Size(1000, 500) - this.Size;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM