Form.AutoSizeMode 属性

定义

获取或设置窗体自动调整自身大小的模式。

C#
[System.ComponentModel.Browsable(true)]
public System.Windows.Forms.AutoSizeMode AutoSizeMode { get; set; }

属性值

AutoSizeMode

AutoSizeMode 枚举值。 默认值为 GrowOnly

属性

例外

该值不是有效的 AutoSizeMode 值。

示例

以下示例显示了使用代码创建的窗体,该表单会自动调整大小以适应其内容。 运行时,窗体将显示一个 Label、一个 TextBox 用于输入 URL,以及一个 Button 用于在用户的默认 Web 浏览器内显示该 URL。 该示例使用一个 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);
}

注解

AutoSizeMode 属性设置为新值会导致窗体再次布局。

无论属性值和AutoSizeMode属性如何,AutoSize窗体都不会在 Visual Studio 窗体设计器中自动调整大小。 根据这两个属性的值,窗体在运行时正确调整自身大小。 相比之下,自定义 UserControl 会在设计时和运行时自动调整自身大小。

适用于

产品 版本
.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

另请参阅