C# 使表单的大小适应其标题文本(C)#

C# 使表单的大小适应其标题文本(C)#,c#,forms,size,titlebar,caption,C#,Forms,Size,Titlebar,Caption,有没有办法使表单的大小适应其标题/标题文本的大小 例如,官方C#消息框表单将根据标题文本的大小进行调整(请注意lorem ipsum): 其他表单不会将其大小调整为其标题文本的大小: 相反,在末尾添加省略号以适合设计器的“size”属性中提到的大小 有没有办法让表格调整到标题的大小而不是我们提到的大小?如果没有,是否有办法获得文本的完整长度,以便我们可以将其分配给表单 我尝试使用 int topTextWidth = TextRenderer.MeasureText(this.Text,

有没有办法使表单的大小适应其标题/标题文本的大小

例如,官方C#消息框表单将根据标题文本的大小进行调整(请注意lorem ipsum):

其他表单不会将其大小调整为其标题文本的大小:

相反,在末尾添加省略号以适合设计器的“size”属性中提到的大小

有没有办法让表格调整到标题的大小而不是我们提到的大小?如果没有,是否有办法获得文本的完整长度,以便我们可以将其分配给表单

我尝试使用

int topTextWidth =  TextRenderer.MeasureText(this.Text, this.Font).Width;
this.Width = topTextWidth;

但是
这个.Font
显然是指另一种字体大小。

对于那些想要完整答案的人,这里就是

根据标题文本调整表单大小的实际行如下所示:

this.Width = TextRenderer.MeasureText(this.Text, SystemFonts.CaptionFont).Width + AllButtonsAndPadding;
AllButtonsAndPadding
包含所有按钮的宽度(最小化、最大化和关闭)、窗口边框和图标。获取这些信息需要一些编码。下面是一个表单的完整示例,它可以调整自身大小,无论您放置了什么按钮或图标

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Forms.VisualStyles;

namespace WindowAutoAdapt
{
public partial class Form1 : Form
{
    //A default value in case Application.RenderWithVisualStyles == false
    private int AllButtonsAndPadding = 0;
    private VisualStyleRenderer renderer = null;

    public Form1()
    {
        InitializeComponent();
        this.Text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit."; //A big text in the title
        GetElementsSize();
        ResizeForm();
    }

    //This gets the size of the X and the border of the form
    private void GetElementsSize()
    {
        var g = this.CreateGraphics();

        // Get the size of the close button.
        if (SetRenderer(VisualStyleElement.Window.CloseButton.Normal))
        {
            AllButtonsAndPadding += renderer.GetPartSize(g, ThemeSizeType.True).Width;
        }

        // Get the size of the minimize button.
        if (this.MinimizeBox && SetRenderer(VisualStyleElement.Window.MinButton.Normal))
        {
            AllButtonsAndPadding += renderer.GetPartSize(g, ThemeSizeType.True).Width;
        }

        // Get the size of the maximize button.
        if (this.MaximizeBox && SetRenderer(VisualStyleElement.Window.MaxButton.Normal))
        {
            AllButtonsAndPadding += renderer.GetPartSize(g, ThemeSizeType.True).Width;
        }

        // Get the size of the icon.
        if (this.ShowIcon)
        {
            AllButtonsAndPadding += this.Icon.Width;
        }

        // Get the thickness of the left, bottom, 
        // and right window frame.
        if (SetRenderer(VisualStyleElement.Window.FrameLeft.Active))
        {
            AllButtonsAndPadding += (renderer.GetPartSize(g, ThemeSizeType.True).Width) * 2; //Borders on both side
        }
    }

    //This resizes the form
    private void ResizeForm()
    {
        this.Width = TextRenderer.MeasureText(this.Text, SystemFonts.CaptionFont).Width + AllButtonsAndPadding;
    }

    //This sets the renderer to the element we want
    private bool SetRenderer(VisualStyleElement element)
    {
        bool bReturn = VisualStyleRenderer.IsElementDefined(element);

        if (bReturn && renderer == null)
            renderer = new VisualStyleRenderer(element);
        else
            renderer.SetParameters(element);

        return bReturn;
    }
 }
 }

谢谢@CydrickT,这很有帮助。我有一些修改,当我将它应用到一个窗口时需要做一些修改,该窗口的
FormBorderStyle
FixedDialog
,并且表单上的if
ControlBox==false
(需要try-catch来处理抛出的错误)

另外,即使指定了and图标,某些
FormBorderStyle
也不会显示它们(即使代码基于某些逻辑的ShowIcon==true),因此此版本的代码会对此进行调整

我还添加了一个新的私有属性,该属性将在构造函数中设置的窗口的最小宽度保持为最小宽度(如果已指定),或者保持为设计时宽度(如果未指定)。如果在代码中更改了窗口的文本(标题),然后重新显示窗体,则可以缩小窗口的宽度

我为表单的文本添加了一个文本更改方法:
Form1\u TextChanged()
,这样每当表单的标题文本更改时,表单的宽度都会调整(如果再次使用表单实例)。当然,表单的设计者需要为要使用的文本更改事件设置此选项

using System;
using System.Drawing;
using System.Windows.Forms;
using System.Windows.Forms.VisualStyles;

namespace WindowAutoAdapt
{
    public partial class Form1: Form
    {
        private int AllButtonsAndPadding = 10;//seems things are coming up about this amount short so.  . .
        private VisualStyleRenderer renderer = null;
        private int minWidth = 0;//will hold either the minimum size width if specified or the design time width of the form.

        public Form1()
        {
            InitializeComponent();

            //Capture an explicit minimum width if present else store the design time width.
            if (this.MinimumSize.Width > 0)
            {
                minWidth = this.MinimumSize.Width;//use an explicit minimum width if present.
            }
            else
            {
                minWidth = this.Size.Width;//use design time width
            }

            GetElementsSize();
            ResizeForm();
        }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void Form1_TextChanged(object sender, EventArgs e)
    {
        GetElementsSize();
        ResizeForm();
    }

        //This gets the size of the X and the border of the form
        private void GetElementsSize()
        {
            var g = this.CreateGraphics();

            // Get the size of the close button.
            if (SetRenderer(VisualStyleElement.Window.CloseButton.Normal))
            {
                AllButtonsAndPadding += renderer.GetPartSize(g, ThemeSizeType.True).Width;
            }

            // Get the size of the minimize button.
            if (this.MinimizeBox && SetRenderer(VisualStyleElement.Window.MinButton.Normal))
            {
                AllButtonsAndPadding += renderer.GetPartSize(g, ThemeSizeType.True).Width;
            }

            // Get the size of the maximize button.
            if (this.MaximizeBox && SetRenderer(VisualStyleElement.Window.MaxButton.Normal))
            {
                AllButtonsAndPadding += renderer.GetPartSize(g, ThemeSizeType.True).Width;
            }

            // Get the size of the icon only if it is actually going to be displayed.
            if (this.ShowIcon && this.ControlBox && (this.FormBorderStyle == FormBorderStyle.Fixed3D || this.FormBorderStyle == FormBorderStyle.Sizable || this.FormBorderStyle == FormBorderStyle.FixedSingle))
            {
                AllButtonsAndPadding += this.Icon.Width;
            }

            // Get the thickness of the left and right window frame.
            if (SetRenderer(VisualStyleElement.Window.FrameLeft.Active))
            {
                AllButtonsAndPadding += (renderer.GetPartSize(g, ThemeSizeType.True).Width) * 2; //Borders on both side
            }
        }

        //This resizes the form
        private void ResizeForm()
        {
            //widen window if title length requires it else contract it to the minWidth if required.
            int newWidth = TextRenderer.MeasureText(this.Text, SystemFonts.CaptionFont).Width + AllButtonsAndPadding;
            if (newWidth > minWidth)
            {
                this.Width = newWidth;
            }
            else
            {
                this.Width = minWidth;
            }
        }

        //This sets the renderer to the element we want
        private bool SetRenderer(VisualStyleElement element)
        {
            try
            {
                bool bReturn = VisualStyleRenderer.IsElementDefined(element);
                if (bReturn && renderer == null)
                {
                    renderer = new VisualStyleRenderer(element);
                }
                else
                {
                    renderer.SetParameters(element);
                }
                return bReturn;
            }
            catch (Exception)
            {
                return false;
            }
        }
    }
}
使用系统;
使用系统图;
使用System.Windows.Forms;
使用System.Windows.Forms.VisualStyles;
命名空间窗口自动适应
{
公共部分类Form1:Form
{
private int-allbuttonsandpaidding=10;//似乎这一数量出现了短缺,所以。
私有VisualStyleRenderer=null;
private int minWidth=0;//将保留窗体的最小大小宽度(如果指定)或设计时宽度。
公共表格1()
{
初始化组件();
//捕获明确的最小宽度(如果存在),否则存储设计时宽度。
如果(this.MinimumSize.Width>0)
{
minWidth=this.MinimumSize.Width;//如果存在,请使用显式最小宽度。
}
其他的
{
minWidth=this.Size.Width;//使用设计时宽度
}
GetElementsSize();
ResizeForm();
}
/// 
/// 
/// 
/// 
/// 
私有void Form1\u TextChanged(对象发送方,事件参数e)
{
GetElementsSize();
ResizeForm();
}
//这将获取X的大小和窗体的边框
私有void GetElementsSize()
{
var g=this.CreateGraphics();
//获取关闭按钮的大小。
if(SetRenderer(VisualStyleElement.Window.CloseButton.Normal))
{
AllButtonsAndPadding+=renderer.GetPartSize(g,ThemeSizeType.True).Width;
}
//获取最小化按钮的大小。
if(this.MinimizeBox&&SetRenderer(VisualStyleElement.Window.MinButton.Normal))
{
AllButtonsAndPadding+=renderer.GetPartSize(g,ThemeSizeType.True).Width;
}
//获取最大化按钮的大小。
if(this.MaximizeBox&&SetRenderer(VisualStyleElement.Window.MaxButton.Normal))
{
AllButtonsAndPadding+=renderer.GetPartSize(g,ThemeSizeType.True).Width;
}
//仅当图标实际要显示时才获取其大小。
if(this.ShowIcon&&this.ControlBox&(this.FormBorderStyle==FormBorderStyle.Fixed3D | | this.FormBorderStyle==FormBorderStyle.sizeable | this.FormBorderStyle==FormBorderStyle.FixedSingle))
{
AllButtonsAndPadding+=this.Icon.Width;
}
//获取左右窗框的厚度。
if(SetRenderer(VisualStyleElement.Window.FrameLeft.Active))
{
AllButtonsAndPadding+=(renderer.GetPartSize(g,ThemeSizeType.True).Width)*2;//两侧的边框
}
}
//这将调整窗体的大小
私有void ResizeForm()
{
//如果标题长度需要,则加宽窗口;如果需要,则将窗口收缩为最小宽度。
int newWidth=TextRenderer.MeasureText(this.Text,SystemFonts.CaptionFont).Width+allbuttonsandpaidding;
如果(新宽度>最小宽度)
{
this.Width=newWidth;
}
其他的
{
这个.Width=minWidth;
}
}
//这会将渲染器设置为所需的元素
私有布尔集合渲染器(VisualStyleElement元素)
{
尝试
{
bool-bReturn=VisualStyleRenderer.IsElementDefined(元素);
if(bReturn&&renderer==null)
{
渲染器=新的VisualStyleRenderer(元素);
}
其他的
{