如何保持字体的继承文本框?文本框、字体

2023-09-03 21:15:59 作者:灵魂摆渡人.

我用下面的code以获得一个TextBox未绘制其边框:

I'm using the following code to get a TextBox that is not drawing its borders:

public partial class CustomTextBox : TextBox
{
	public CustomTextBox()
	{
		InitializeComponent();
		SetStyle(ControlStyles.UserPaint, true);
	}

	protected override void OnPaint(PaintEventArgs e)
	{
		base.OnPaint(e);

		int borderWidth = 1;

		ControlPaint.DrawBorder(e.Graphics, e.ClipRectangle,
		    Color.Transparent, borderWidth, ButtonBorderStyle.Solid,
		    Color.Transparent, borderWidth, ButtonBorderStyle.Solid,
		    Color.Transparent, borderWidth, ButtonBorderStyle.Solid,
		    Color.Transparent, borderWidth, ButtonBorderStyle.Solid);
	}
}

我好像错过了什么的OnPaint()内部,因为我的字体不是默认字体的文本框了(也许是我要重写另一个事件)。

I seem to miss something inside of OnPaint() because my Font is not the default Font for a textBox anymore (perhaps I have to override another event).

当检查CustomTextBox.Font财产它让我看到默认的Microsoft SANSSERIF在8,25,但键入文本到我的textBox当字体肯定看起来更大,加粗。

When checking CustomTextBox.Font property it shows me the default "Microsoft SansSerif in 8,25" but when typing text into my textBox the Font definitely looks bigger and bold.

希望你能帮帮我!

问候,

INNO

我要指出,如果我不重写的OnPaint我CustomTextBox的字体是正确的。只有当压倒一切的OnPaint我的字体是不正确(输入文本时,字体较大,似乎是大胆的)。 因此,我认为我必须做一些事来正确初始化字体的OnPaint内(但ATM我不知道如何做到这一点)。

I should mention that if I don't override OnPaint the Font of my CustomTextBox is correct. Only when overriding OnPaint my Font is incorrect (when typing text the font is bigger and seems to be bold). So I think I have to do something to initialize the font correctly inside of OnPaint (but ATM I have no idea how to do this).

推荐答案

不要调用setStyle如果尚未创建的句柄文本框,它永远不会更改为大粗的字体:

Don't call SetStyle if the handle for the textbox is not yet created, and it won't ever change to that 'big bold' font:

if (IsHandleCreated)
{
     SetStyle(ControlStyles.UserPaint, true);
}