简体   繁体   中英

C# - Stretching a textbox to fit the containing window

I want the text box to stay a certain distance from the top, bottom, left, and right edges of the parent form, and to stretch as the window does.

Currently I have:

private void Form1_SizeChanged(object sender, EventArgs e)
{
    richTextBox1.Size = new System.Drawing.Size(this.ClientSize.Width - 24, richTextBox1.Size.Height);
}

...for the width, but I'm wondering if that's the right way or not. Is there a better way?

As Moozhe said you need Anchor property of the control

Use the Anchor property to define how a control is automatically resized as its parent control is resized. Anchoring a control to its parent control ensures that the anchored edges remain in the same position relative to the edges of the parent control when the parent control is resized.

But also from my experience do not forget to assign MinimumSize and MaximumSize of the control these properties helps for the control to have certain minimum or maximum size if you resize your form too small or too big.

您还可以像这样使用Dock属性:

richTextBox1.Dock = DockStyle.Fill;

这将起作用:

richTextBox1.Anchor = (AnchorStyles.Bottom | AnchorStyles.Right |  AnchorStyles.Left | AnchorStyles.Top);

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