c# - 没有内边距和边距的标签

标签 c# winforms .net-3.5 label

我有以下 C# 代码 (.NET Framework 3.5)

public partial class MainForm : Form
{
    public MainForm()
    {
        //
        // The InitializeComponent() call is required 
        // for Windows Forms designer support.
        //
        Label myControl = new Label();
        myControl.Text = "TEXT";
        myControl.FlatStyle = FlatStyle.System;
        myControl.AutoSize = true;
        myControl.BorderStyle = BorderStyle.FixedSingle;
        myControl.Padding = new Padding(0);
        myControl.Margin = new Padding(0);
        this.Controls.Add(myControl);
        InitializeComponent();
    }
}

它应该显示一个标签,其中的文本由边框包围,如下所示:

------
|TEXT|
------

相反,我得到了这个:

--------
|TEXT  |
--------

我不知道为什么......我的目标是能够有多个标签,它们之间没有空格,如下所示:

-----------
|TEXT|TEXT|
-----------

我错过了什么吗?提前致谢!

为了澄清,我需要在文本和边框之间没有空格。

最佳答案

这就是为我解决的问题(使用@LarsTech的解决方案):

我添加了

    protected override void OnHandleCreated(EventArgs e) {
        base.OnHandleCreated(e);
        this.AutoSize = false;
    }

    protected override void OnFontChanged(EventArgs e) {
        base.OnFontChanged(e);
        this.Size = GetTextSize();
    }

    protected override void OnResize(EventArgs e) {
        base.OnResize(e);
        this.Size = GetTextSize();
    }

    protected override void OnTextChanged(EventArgs e) {
        base.OnTextChanged(e);
        this.Size = GetTextSize();
    }

    private Size GetTextSize() {
        Size padSize = TextRenderer.MeasureText(".", this.Font);
        Size textSize = TextRenderer.MeasureText(this.Text + ".", this.Font);
        return new Size(textSize.Width - padSize.Width, textSize.Height);
    }

我的标签定义。

我还添加了

textLabel.FlatStyle = FlatStyle.System;

非常感谢您的帮助!

关于c# - 没有内边距和边距的标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21632642/

相关文章:

c# - 在 .NET 中存储数据库连接详细信息的最佳做法是什么?

c# - 寻找带有 JSON 客户端库的 REST

c# - 如何检查数字字符串是否在运行序列中

c# - 使用 __doPostBack() 进行回发时遇到错误

c# - 锁 c#2 中抛出的异常

c# - 如何正确打开登录表单

c# - 如何在 C# 中使用 Rest Web 服务

C# 循环和按键中断循环

具有自定义边框和圆边的 C# 窗体

c# - 在 asp.net 中执行存储过程时出错