Trying to auto-resize a winforms button, within another control

nope no 65 Reputation points
2023-04-20T17:07:52.2466667+00:00

As the title states, i have a button anchored to the lower right of a control in the designer. Setting the button to autosize does not change the button's size when the form is resized, furthermore, it is eventually swallowed by the rest of the control. Is there a standard setting in designer that allows the button to resize when the control it is part of, resizes? If it must be done programmatically, how is that done? Thank you.

Developer technologies | Windows Forms
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Jiachen Li-MSFT 34,231 Reputation points Microsoft External Staff
    2023-04-21T05:26:43.1866667+00:00

    Hi @nope no ,

    You can use the SizeChanged event to automatically size other controls.

    The following code uses Form1_SizeChanged as an example to keep the button1 automatically scaled in equal proportion to Form1.

            float firstWidth;
            float firstHeight;
    
            private void Form1_SizeChanged(object sender, EventArgs e)
            {
                float size1 = this.Size.Width / firstWidth;
                float size2 = this.Size.Height / firstHeight;
    
                SizeF scale = new SizeF(size1, size2);
                firstWidth = this.Size.Width;
                firstHeight = this.Size.Height;
    
                button1.Font = new System.Drawing.Font(button3.Font.FontFamily, button3.Font.Size * ((size1 + size2) / 2));
    
                button1.Scale(scale);
            }
    
            private void Form1_Load(object sender, EventArgs e)
            {
                firstWidth = this.Size.Width;
                firstHeight = this.Size.Height;
            }
    

    Best Regards.

    Jiachen Li


    If the answer is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


  2. Deleted

    This answer has been deleted due to a violation of our Code of Conduct. The answer was manually reported or identified through automated detection before action was taken. Please refer to our Code of Conduct for more information.


    Comments have been turned off. Learn more

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.