我有以下 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/