如何在继承的TextBox中保留Font?

2024-02-15

我使用以下代码来获取未绘制边框的 TextBox:

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() 内部的某些内容,因为我的字体不再是文本框的默认字体(也许我必须重写另一个事件)。

当检查 CustomTextBox.Font 属性时,它显示默认的“Microsoft SansSerif in 8,25”,但是当在我的文本框中输入文本时,字体肯定看起来更大、更粗。

希望你能帮我!

Regards,

inno

[EDIT]

我应该提到,如果我不重写 OnPaint,我的 CustomTextBox 的字体是正确的。仅当覆盖 OnPaint 时,我的字体不正确(输入文本时字体更大并且看起来是粗体)。 所以我想我必须做一些事情来在 OnPaint 内正确初始化字体(但 ATM 我不知道如何做到这一点)。


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

if (IsHandleCreated)
{
     SetStyle(ControlStyles.UserPaint, true);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在继承的TextBox中保留Font? 的相关文章

随机推荐