AutoSizeMode 枚举

定义

指定启用控件的 AutoSize 属性时该控件的行为。

C#
public enum AutoSizeMode
继承
AutoSizeMode

字段

GrowAndShrink 0

控件根据它的内容增大或缩小。 不能手动调整该控件的大小。

GrowOnly 1

控件可以根据其内容任意增大,但不会缩小至小于它的 Size 属性值。 窗体可以调整大小,但不能缩小到它所包含的任意控件被隐藏。

示例

下面的代码示例显示了使用代码创建的窗体,该表单会自动调整大小以适应其内容。 运行后,窗体将显示一个 Label、一个 TextBox 用于输入 URL 和一个 Button 用于在用户的默认 Web 浏览器内显示该 URL。 代码示例使用 a 一 FlowLayoutPanel 个来布局包含的控件,并设置 AutoSizeAutoSizeMode 增大和缩小以适应其形式的内容。

C#
private void Form1_Load(object sender, EventArgs e)
{
    this.AutoSize = true;
    this.AutoSizeMode = AutoSizeMode.GrowAndShrink;
    this.Text = "URL Opener";

    flowPanel = new FlowLayoutPanel();
    flowPanel.AutoSize = true;
    flowPanel.AutoSizeMode = AutoSizeMode.GrowAndShrink;
    this.Controls.Add(flowPanel);

    urlLabel = new Label();
    urlLabel.Name = "urlLabel";
    urlLabel.Text = "URL:";
    urlLabel.Width = 50;
    urlLabel.TextAlign = ContentAlignment.MiddleCenter;
    flowPanel.Controls.Add(urlLabel);

    urlTextBox = new TextBox();
    urlTextBox.Name = "urlTextBox";
    urlTextBox.Width = 250;
    flowPanel.Controls.Add(urlTextBox);

    urlButton = new Button();
    urlButton.Name = "urlButton";
    urlButton.Text = "Open URL in Browser";
    urlButton.Click += new EventHandler(urlButton_Click);
    flowPanel.Controls.Add(urlButton);
}

void urlButton_Click(object sender, EventArgs e)
{
    try
    {
        Uri newUri = new Uri(urlTextBox.Text);
    }
    catch (UriFormatException uriEx)
    {
        MessageBox.Show("Sorry, your URL is malformed. Try again. Error: " + uriEx.Message);
        urlTextBox.ForeColor = Color.Red;
        return;
    }
    
    // Valid URI. Reset any previous error color, and launch the URL in the 
    // default browser.
    // NOTE: Depending on the user's settings, this method of starting the
    // browser may use an existing window in an existing Web browser process.
    // To get around this, start up a specific browser instance instead using one of
    // the overloads for Process.Start. You can examine the registry to find the
    // current default browser and launch that, or hard-code a specific browser.
    urlTextBox.ForeColor = Color.Black;
    Process.Start(urlTextBox.Text);
}

注解

设置 GrowAndShrink 值会生成与启用属性但未启用属性的控件 AutoSize 相同的行为

AutoSizeMode 属性。 遵循 MinimumSize 属性和 MaximumSize 属性,但忽略该属性的 Size 当前值。

适用于

产品 版本
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8
Windows Desktop 3.0, 3.1, 5, 6, 7

另请参阅